Ajaxed Sliding Shopping Cart With jQuery

27°

With this 5th & last post of the "WRD E-Commerce Week" we will be modifying "our Ajaxed shopping cart" to create a one which is very ideal for designs with limited spaces.

The shopping cart will:

  • be hidden at the top of the page that can be displayed with a show/hide link
  • open when an item is added to the basket & auto-close
  • require a manual "hide" click if opened manually
  • enable us to delete products

Ajaxed Sliding Shopping Cart

Download

The HTML

For The Sliding Basket:

[sourcecode language=”php”]

Your Basket
  •  

[/sourcecode]

The Highlights

  • the div slidingTopWrap is positioned absolutely with top: 0 CSS value to stick to the top of the page
  • the div slidingTopContent is hided via JavaScript when the page loads & it is actually the part which slides
  • the div basketWrap, nothing unusual, wraps the contents of the basket

The JavaScript (jQuery)

Manual Show/Hide Part

[sourcecode language=”javascript”]
$(“#basketItemsWrap li:first”).hide();
$(“#slidingTopContent”).hide();

$(“#slidingTopTrigger”).live(“click”, function(event) {
$(“#slidingTopContent”).slideToggle(“slow”, function(){
if ($(“#slidingTopContent”).is(“:visible”)) {
$(“#slidingTopFooterLeft”).html(‘Hide Basket Hide Basket‘);
} else {
$(“#slidingTopFooterLeft”).html(‘Show Basket Show Basket‘);
}
});
});

[/sourcecode]

The Highlights:

  • we have $("#slidingTopContent").hide(); in the beginning to hide the div in the initial load
  • when the #slidingTopTrigger is clicked, we use the slideToggle function to show/hide the #slidingTopContent. To understand whether it is open or not, we have an if then else clause as if ($("#slidingTopContent").is(":visible")) {
    • if the #slidingTopContent is visible, we insert the "hide HTML"
    • if the #slidingTopContent is not visible, we insert the "show HTML"
  • you'll see that we used the $("#slidingTopTrigger").live("click", function(event) { rather than a standard click function. The reason is adding the new created HTMLs to the DOM

Adding Products

[sourcecode language=”javascript”]
$(“.productPriceWrapRight a img”).click(function() {
var productIDValSplitter = (this.id).split(“_”);
var productIDVal = productIDValSplitter[1];

if ($(“#slidingTopContent”).is(“:visible”)) {

$(“#notificationsLoader”).html(‘‘);

$.ajax({
type: “POST”,
url: “inc/functions.php”,
data: { productID: productIDVal, action: “addToBasket”},
success: function(theResponse) {

if( $(“#productID_” + productIDVal).length > 0){
$(“#productID_” + productIDVal).animate({ opacity: 0 }, 500);
$(“#productID_” + productIDVal).before(theResponse).remove();
$(“#productID_” + productIDVal).animate({ opacity: 0 }, 500);
$(“#productID_” + productIDVal).animate({ opacity: 1 }, 500);
$(“#notificationsLoader”).empty();

} else {
$(“#basketItemsWrap li:first”).before(theResponse);
$(“#basketItemsWrap li:first”).hide();
$(“#basketItemsWrap li:first”).show(“slow”);
$(“#notificationsLoader”).empty();
}

}
});

} else {

$(“#slidingTopContent”).slideToggle(“slow”, function(){

$(“#slidingTopFooterLeft”).html(‘Hide Basket Hide Basket‘);
$(“#notificationsLoader”).html(‘‘);

$.ajax({
type: “POST”,
url: “inc/functions.php”,
data: { productID: productIDVal, action: “addToBasket”},
success: function(theResponse) {

if( $(“#productID_” + productIDVal).length > 0){
$(“#productID_” + productIDVal).animate({ opacity: 0 }, 500);
$(“#productID_” + productIDVal).before(theResponse).remove();
$(“#productID_” + productIDVal).animate({ opacity: 0 }, 500);
$(“#productID_” + productIDVal).animate({ opacity: 1 }, 500);
$(“#notificationsLoader”).empty();

} else {
$(“#basketItemsWrap li:first”).before(theResponse);
$(“#basketItemsWrap li:first”).hide();
$(“#basketItemsWrap li:first”).show(“slow”);
$(“#notificationsLoader”).empty();
}

}
});

$(“#slidingTopTrigger”).fadeTo(4000, 1, function(){
$(“#slidingTopContent”).slideToggle(“slow”, function(){
$(“#slidingTopFooterLeft”).html(‘Show Basket Show Basket‘);
});

});

});
}

});

[/sourcecode]

The Highlights:

As "how-to" on sending the Ajax query & fading animations are described in the previous post, we won't repeating the same info here & focus on the effects.

  • we again run the same if-then-else clause
    • if the #slidingTopContent is open send an Ajax query to functions.php and add-the-products to basket
    • if the #slidingTopContent is closed:
      • slideToggle the div
      • insert the "hide HTML" to #slidingTopFooterLeft"
      • send an Ajax query to functions.php and add-the-products to basket
      • wait for x seconds: $("#slidingTopTrigger").fadeTo(4000, 1, function(){
      • slideToggle the div
      • insert the "show HTML" to #slidingTopFooterLeft"

P.S. To make the example work on your side, you should be creating a new database with the jBasket.sql file inside the download package & configure the database connection information inside “inc/db.php” file.

47 Comments
  1. Reply dejan July 31, 2009 at 1:24 PM

    Nice post, thx.
    Anyway, i’m rss subscribed and yet cannot find the link for downloading, even for the previous post “Fly-To-Basket Effect With jQuery”.
    Am i missing something?

  2. Reply Umut M. July 31, 2009 at 1:50 PM

    @dejan,

    Great that you liked it.

    The download link is at: when viewing the post via RSS> at the bottom of the latest post>Under Special Downloads Title> Ajaxed Add-To-Basket Scenarios With jQuery And PHP

    Kinda complicated I think :), maybe I should place them as a standard download or think something easier by still combining with RSS.

  3. Reply Dean Higginbotham July 31, 2009 at 6:13 PM

    Good timing, I just built this into one of the sites I did: http://www.hotcakes.com/46 is an example.

    It’s drag-drop however….er…well, It’s both I guess since you can click the “add to shopping list” from the item detail too…and compare area as well.

    The idea is awesome and a great space saver.

  4. Reply dejan July 31, 2009 at 9:37 PM

    Umut, thx.
    The problem is on my side, since i thought that the link is referring to the previously posted script named “Fly-To-Basket Effect With jQuery”.

    Thanks again

  5. Reply Brian Jørgensen August 1, 2009 at 6:44 AM

    Hi, thanks for this tutorial.

    But there seems to be a problem every time I push Hide basket it goes up but then down again – that means I have to push Show basket for it to go up. That’s strange.

    But cool effect and I like it though.

  6. Reply Umut M. August 3, 2009 at 5:51 AM

    @Brian,

    Ok, I found when & why it happens:
    Once a product is added to the cart, it slides and before it automatically hides, if you hide it manually then the auto-hide becomes, auto show.

    I will add a simple if then else clause which will solve it.

  7. Reply Grapher September 2, 2009 at 2:33 AM

    Hi, thanx for sharing)
    very elegant and usefull

  8. Reply xaviergnu October 1, 2009 at 8:39 AM

    Hi all,

    excellent script, although I came up with the following problem:

    I have a form that picks up products options (radio buttons, checkboxes…) and then calculates a price of a product to be inserted in a shopping basket.

    Since the present link is posting values via ‘a href’ tag through ‘functions.php?id=foo’ what should I change to get it done with submitting form??

    any clues,

    thanx in advance,

    X

  9. Reply bharanikumar October 27, 2009 at 12:33 PM

    i am doing to mobile service center application ,

    i want something like multiple combo

    combo 1 ==> Mobilebrand

    combo 2 ==> MobilebrandModel

    combo 3 ==> Problem name

    Display amount for this service,

    Add to cart button .

    How to customise the about cart …

    Thanks

  10. Reply Hakan Sahin December 24, 2009 at 11:30 PM

    Thanks a lot for this nice script. If you have a lot of products on the same page and want the basket to auto-scroll with the page then a little CSS trick will do the trick without needing any extra JavaScript. Here is the code to change:

    Go to file inc/style.css and change the following part:

    #slidingTopWrap {
    position: fixed; /* enable auto-scrolling of the basket with the page */
    /* position: absolute; default-> basket fixed where it is! */

  11. Reply Umut M. December 25, 2009 at 12:55 AM

    @Hakan,

    Thanks very much for that, nice tip.

  12. Reply nikhil February 8, 2010 at 5:22 AM

    nice script….
    thankx for sharing it…..

  13. Reply egar February 9, 2010 at 6:05 PM

    hello i still cant find the download link in http://feeds2.feedburner.com/webresourcesdepot at line special download

  14. Reply Umut M. February 10, 2010 at 1:53 AM

    @egar,
    It is placed at the bottom of any post that is read via RSS.

  15. Reply sutou February 23, 2010 at 3:49 AM

    how to download???

  16. Reply celine February 26, 2010 at 5:40 AM

    I just can’t get it working, could somebody please help me?
    http://www.celinekurpershoek.nl/project/goudse_stroopwafel/pages/assortiment.php

  17. Reply redd March 17, 2010 at 4:39 AM

    hi i was wondering how to update a total price using the standard version

    i have it updating when a user adds items to the basket by inserting this in the addtobasket action

    if ($action == “addToBasket”){

    $productInBasket = 0;
    $productTotalPrice = 0;

    $query = “SELECT DISTINCT * FROM products WHERE productID = ” . $productID;
    $result = mysql_query($query);
    $row = mysql_fetch_array( $result );

    $productPrice = $row[‘productPrice’];
    $productName = $row[‘productName’];

    $query = “INSERT INTO baskets (productID, productPrice, basketSession) VALUES (‘$productID’, ‘$productPrice’, ‘$sessionID’)”;
    mysql_query($query) or die(‘Error, insert query failed’);

    $query = “SELECT DISTINCT * FROM baskets WHERE productID = ” . $productID . ” AND basketSession = ‘” . $sessionID . “‘”;
    $result = mysql_query($query) or die(mysql_error());;

    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
    $totalItems = $totalItems + 1;
    $productTotalPrice = $productTotalPrice + $row[‘productPrice’];
    }

    if ($noJavaScript == 1) {
    header(“Location: ../index.php”);
    } else {
    echo (‘ ‘ . $productName . ‘(‘ . $totalItems . ‘ items) – $’ . $productTotalPrice . ”);
    }
    ?>

    document.getElementById(“price”).innerHTML=””;

    <?php
    }

    but adding the same script clause in the deletebasket area doesnt work the same, any suggestions ?

  18. Reply Bob June 2, 2010 at 5:04 AM

    Hi,

    Great script. Almost sorted now. Just wondered if I could somehow stop the basket from dropping down and showing contents each time someone visits a page. I’d like it only to reveal the contents of the basket when someone actually clicks on the ‘Show Basket’ link.

    Any ideas would be great.

    Thanks

    Bob

  19. Reply james July 14, 2010 at 9:24 PM

    Hi thanks for sharing! looks stunning!
    is there any way to implement this with OScommerce?
    i cuurently have an ecommerce and i would love to implement that…

  20. Reply Kate August 19, 2010 at 4:03 PM

    Hi i loved this script so much!
    But i was trying to change the name of the items in the basket . and i don’t know how to! any help with this?
    Thanks again for this lovely script 🙂

  21. Reply Umut M. August 20, 2010 at 7:40 AM

    @Kate,

    The name of the items should be updated from the MySQL database (you need a db admin tool like phpMyAdmin for that).

  22. Reply nagesh hyalij September 3, 2010 at 4:06 AM

    Fatal error: Call to undefined function q() in C:\xampp\htdocs\projects\addtocart\inc\functions.php on line 67

    as i integrated code with my DB on local machine.
    all functionalties are working fine.

    but its showing me an error. at line
    $sel_query = q(“SELECT * FROM baskets WHERE basketSession = ‘” . $sessionID . “‘ GROUP BY productID ORDER By basketID DESC”);

  23. Reply Tom October 5, 2010 at 8:15 AM

    Is there any way to have the jquery-1.3.2.min.js code working alonside jqModal.js script?

    I’ve found the jquery-1.3.2.min.js code obstructs many other type of jQuery style codes..

  24. Reply jcubic October 21, 2010 at 4:03 PM

    Great demo I got 8 Notices and 3 warnings from php.
    Good job 🙂

  25. Reply nashekrashe November 8, 2010 at 7:36 AM

    works perfectly at http://bookilla.com/

  26. Reply Lisa November 9, 2010 at 7:52 AM

    Your demo page has the PHP notices and warnings set to display. This isn’t very good practice for a production site.

  27. Reply shivi January 25, 2011 at 2:38 AM

    Sir,

    i want this shopping cart in .net not in php. I want to implement this shopping cart into my .net project. Please help me

  28. Reply Denis April 3, 2011 at 11:14 AM

    Hello, it’s a great script but I have a question! Why the “totalItems” don’t seen all the time? It’s apeared only when I add the product!

  29. Reply dunn May 4, 2011 at 9:41 PM

    How do you go about installing this script to a wordpress / wp ecommerce powered site?

  30. Reply Bruno Oluka May 8, 2011 at 1:29 PM

    Thanks for sharing this script. However i would have loved if you included checking out and redirect the buyer to paypal to make their payments.

  31. Reply Rui Gomes June 1, 2011 at 5:59 AM

    Hi,
    I need to add a GRAND TOTAL (always viewable), how can i do this?
    At this moment i´ve this, but i´ve to refresh the page to see the total…

    [code]
    (inside the function getBasket(), at the bottom)
    $query3 = “SELECT *,SUM(productPrice) FROM baskets WHERE basketSession = ‘” . $sessionID . “‘GROUP BY basketSession”;
    $result3 = mysql_query($query3);
    $row3 = mysql_fetch_array($result3, MYSQL_ASSOC);
    if ($row3[‘SUM(productPrice)’] > 0) {
    $basketText.=’Total: ‘.$row3[‘SUM(productPrice)’].’€‘;
    }

    [/code]

    ps – it´s urgent 🙂

    Regards,
    RG

  32. Reply Bill Tudor June 20, 2011 at 6:15 AM

    I have learnt a lot from your script which is working really nicely apart from one thing (which is mentioned by someone called Bob above). Sometimes the Bag shows and hides real quick like a flicker when you come to the site for the first time. Is this to do with the logic of hide() and show() ? Thanks agian though for providing an excellent example script.

  33. Reply Umut M. June 21, 2011 at 6:12 AM

    @Bill,

    Yes, it displays the cart until the JavaScript code (that hides it) is loaded by the browser.

    It can be a good idea to hide it with CSS (rather than JavaScript) at first.

  34. Reply Bill Tudor June 22, 2011 at 9:40 AM

    Umut,

    Thanks for the reply & I will try what you suggest. But I also have the same another little ‘niggle’ which Brian Jorgensen (Aug 2009) mentions above; Could you explain your fix; where you say…”Once a product is added to the cart, it slides and before it automatically hides, if you hide it manually then the auto-hide becomes, auto show. I will add a simple if then else clause which will solve it.”

    What is that simple if..then..else clause? Many thanks.

  35. Reply Raul July 24, 2011 at 11:30 AM

    Hey dude, im having some problems when i go to other section of my site, the items and price get lost, till the moment i choose other item i can see again te price and number of items. And i was trying to keep them by $_SESSION, but not having success, can you help me please?

    Thanks. Regards.

  36. Reply Umut M. July 25, 2011 at 2:46 AM

    @Raul,

    Although not sure, I think you should call the getBasket function on initial load of the web pages.

  37. Reply Daniel August 31, 2011 at 9:34 AM

    It is a great tutorial ever!
    However, I found some problems in this program.

    When the variable $nojavascript in functions.php equal to ‘1’, the hyperlink of ‘show/hide’ will become ‘no-js.htm’ and ‘aaa.htm’, what it suppose to be??

    Thanks again for providing an excellent example script.

  38. Reply gert November 8, 2011 at 8:02 AM

    is it posible to put in the quantity of ordered goods before you hit the “add to basket” ?

  39. Reply Caleb February 23, 2012 at 3:36 PM

    nice piece of code but is there a way to get it to slide up from the bottom of the page instead of sliding down from the top of the page

  40. Reply Alec February 27, 2012 at 6:36 AM

    I am planning on adding a “Checkout” button to the basket, but how can i show the data of the basket on the checkout page in a table, and then send that data to paypal, google checkout or http://www.2checkout.com

  41. Reply Umut M. February 29, 2012 at 10:13 AM

    @Alec,

    As the records are kept in the database, you should better be creating a custom “post” structure where the latest “post data” is pulled from the database.

  42. Reply Lau King Lieng March 2, 2012 at 12:03 PM

    may i know how to make a confirmation before confirm the order and after confirm will automatically insert into mysql database

  43. Reply Jinu Elsa James May 9, 2012 at 6:01 AM

    i want this shopping cart in .net not in php. I want to implement this shopping cart into my .net project. Please help me

  44. Reply Fred July 18, 2012 at 6:43 AM

    Hi,
    Your sliding cart is really great.
    I would like it to follow the page scroll, but I don’t know how to do this, could you please help me?
    Best regards

  45. Reply Droopy March 8, 2013 at 10:57 AM

    Hello
    Is it possible to change the custom.js to have the sliding effect with the fly effect ?
    and how ?
    thank’s

  46. Reply Oki November 25, 2015 at 2:57 AM

    this source download problem. My mail adress send Download link please.

Leave a reply

Search