Drag Drop Shopping Cart Using JQuery

April 2nd, 2011 by aditia rahman / 26 Comments  

     

There are a lot tutorial about creating drag and drop shopping cart, in this post I want to share my version still with JQuery, but the different is this example only shows the code on the client side, which mean all of data are hardcoded on the html, and counting price and total items will be handle by javascript.

jquery drag drop shopping cart

The drag and drop feature used from JQuery UI, this will be used on the item list and on the cart item list to see all the items on the cart by dragging the cart horizontally.

View Demo | Download Source

The Html

Default Item List

Like I said there is no server side scripting, so this code just a hardcoded item list, this example use 10 items, but the code below shows only two to make it simple.

<div id="item_container">
      <div class="item" id="i1">
          <img src="img/1.jpg"/>
          <label class="title">T-Shirt 1</label>
          <label class="price">$ 20</label>
      </div>
      <div class="item" id="i2">
          <img src="img/2.jpg"/>
          <label class="title">T-Shirt 2</label>
          <label class="price">$ 24</label>
      </div>
      <div class="clear"></div>
  </div>

Shopping Cart

In shopping cart element, there are element for dropped item area, this area will be draggable so all the items can be shown and there also a navigate for clearing cart, total items and total price.

<div id="cart_container">
  <div id="cart_title">
      <span>Shopping Cart</span>
      <div class="clear"></div>
  </div>
  <div id="cart_toolbar">
      <div id="cart_items" class="back"></div>
  </div>
  <div id="navigate">
      <div id="nav_left">
          <a href="" id="btn_prev"><</a>
          <a href="" id="btn_next">></a>
          <a href="" id="btn_clear">Clear Cart</a>
      </div>
      <div id="nav_right">
          <span class="sptext">
              <label>Items </label><label class="count" id="citem">0</label>
          </span>
          <span class="sptext">
              <label>Price </label><label class="count" id="cprice">$ 0</label>
          </span>
      </div>
      <div class="clear"></div>
  </div>
</div>
The JQuery

Intializing The Cart

This initializing code for setting up the draggable item on item list, draggable shopping cart and the action after an item dropped on the cart like updating total item, total price and setting up remove link in each item.

var total_items = 0;
var total_price = 0;
$(document).ready(function() {

    $(".item").draggable({
        revert: true
    });
    $("#cart_items").draggable({
        axis: "x"
    });

    $("#cart_items").droppable({
        accept: ".item",
        activeClass: "drop-active",
        hoverClass: "drop-hover",
        drop: function(event, ui) {
            var item = ui.draggable.html();
            var itemid = ui.draggable.attr("id");
            var html = '<div class="item icart">';
            html = html + '<div class="divrm">';
            html = html + '<a onclick="remove(this)" class="remove '+itemid+'">&times;</a>';
            html = html + '<div/>'+item+'</div>';
            $("#cart_items").append(html);

            // update total items
            total_items++;
            $("#citem").html(total_items);

            // update total price
            var price = parseInt(ui.draggable.find(".price").html().replace("$ ", ""));
            total_price = total_price + price;
            $("#cprice").html("$ " + total_price);

            // expand cart items
            if (total_items > 4) {
                $("#cart_items").animate({width: "+=120"}, 'slow');
            }
        }
    });
});

Removing An Item

When removing an item the total price and total items are updated and of course the item removed from the cart.

function remove(el) {
    $(el).hide();
    $(el).parent().parent().effect("highlight", {color: "#ff0000"}, 1000);
    $(el).parent().parent().fadeOut('1000');
    setTimeout(function() {
        $(el).parent().parent().remove();
        // collapse cart items
        if (total_items > 3) {
            $("#cart_items").animate({width: "-=120"}, 'slow');
        }
    }, 1100);

    // update total item
    total_items--;
    $("#citem").html(total_items);

    // update totl price
    var price = parseInt($(el).parent().parent().find(".price").html().replace("$ ", ""));
    total_price = total_price - price;
    $("#cprice").html("$ " + total_price);
}

Navigate Cart

Dragging the cart is not the only way to navigate through all the cart, so I adding the two links to seeing all items on the cart, these links just manipulating the left CSS property.

$("#btn_next").click(function() {
    $("#cart_items").animate({left: "-=100"}, 100);
    return false;
});
$("#btn_prev").click(function() {
    $("#cart_items").animate({left: "+=100"}, 100);
    return false;
});
$("#btn_clear").click(function() {
    $("#cart_items").fadeOut("2000", function() {
       $(this).html("").fadeIn("fast").css({left: 0});
    });
    $("#citem").html("0");
    $("#cprice").html("$ 0");
    total_items = 0;
    total_price = 0;
    return false;
});
The CSS
body {
    font-family: Arial, "Free Sans";
    margin: 0;
    padding: 0;
}
#item_container {
    width: 610px;
    margin: 0 auto;
    margin-top: 10px;
    margin-bottom: 10px;
}
.item {
    background: #fff;
    float: left;
    padding: 5px;
    margin: 5px;
    cursor: move;
    -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.5);
    -moz-box-shadow: 0 1px 2px rgba(0,0,0,.5);
    box-shadow: 0 1px 2px rgba(0,0,0,.5);
    -webkit-border-radius: .5em;
    -moz-border-radius: .5em;
    border-radius: .5em;
    z-index: 5;
}
.title, .price {
    display: block;
    text-align: center;
    font-size: 14px;
    letter-spacing: -1px;
    font-weight: bold;
    cursor: move;
}
.title {
    color: #333;
}
.price {
    color: #0099cc;
    margin-top: 5px;
    -webkit-border-radius: .5em;
    -moz-border-radius: .5em;
    border-radius: .5em;
}
.icart, .icart label {
    cursor: e-resize;
}
.divrm {
    text-align: right;
}
.remove {
    text-decoration: none;
    cursor: pointer;
    font-weight: bold;
    font-size: 20px;
    position: relative;
    top: -7px;
}
.remove:hover {
    color: #999;
}
.clear {
    clear: both;
}
#cart_container {
    margin: 0 auto;
    width: 495px;
}
#cart_title span {
    border: 8px solid #666;
    border-bottom-width: 0;
    background: #333;
    display: block;
    float: left;
    color: #fff;
    font-size: 11px;
    font-weight: bold;
    padding: 5px 10px;
    -webkit-border-radius: .5em .5em 0 0;
    -moz-border-radius: .5em .5em 0 0;
    border-radius: .5em .5em 0 0;
}
#cart_toolbar {
    overflow: hidden;
    border: 8px solid #666;
    height: 190px;
    z-index: -2;
    width: 483px;
    -webkit-border-radius: 0 .5em 0 0;
    -moz-border-radius: 0 .5em 0 0;
    border-radius: 0 .5em 0 0;
    background: #ffffff;
}
#cart_items {
    height: 190px;
    width: 483px;
    position: relative;
    padding: 0 0 0 2px;
    z-index: 0;
    cursor: e-resize;
    border-width: 0 2px;
}
.back {
    background: #e9e9e9;
}
#navigate {
    width: 463px;
    margin: 0 auto;
    border: 8px solid #666;
    border-top-width: 0;
    -webkit-border-radius: 0 0 .5em .5em;
    -moz-border-radius: 0 0 .5em .5em;
    border-radius: 0 0 .5em .5em;
    padding: 10px;
    font-size: 14px;
    background: #333;
    font-weight: bold;
}
#nav_left {
    float: left;
}
#nav_left a {
    padding: 4px 8px;
    background: #fff;
    -webkit-border-radius: .5em;
    -moz-border-radius: .5em;
    border-radius: .5em;
    text-decoration: none;
    color:#0099cc;
}
#nav_left a:hover {
    background: #666;
    color: #fff;
}
#nav_right {
    float: right;
}
.sptext {
    background: #ffffff;
    padding: 4px 8px;
    margin-left: 8px;
    -webkit-border-radius: .5em;
    -moz-border-radius: .5em;
    border-radius: .5em;
    color: #666;
}
.count {
    color: #0099cc;
}
.drop-active {
    background: #ffff99;
}
.drop-hover {
    background: #ffff66;
}

And here are the result and the links for viewing the demo and download the code.

jquery drag drop shopping cart

View Demo | Download Source

This is the unsual shopping cart I think, but some online store I see using this kind of shopping cart, but they put it on the bottom with CSS fixed position, I forgot what the site are. Last, this link in case you want to see the drag n drop cart in extjs.

        submit to reddit Delicious

26 Comments Leave a Comment Subscribe RSS

  • Pointless says:

    Pointless! Just copying text and code from jQuery UI.

  • Mary Jane Rutkowski says:

    I like this approach. I think it can be useful for providing a library of related materials. Users could then drag the “covers” of the reports they would like to read into the shopping cart. Instead of purchasing, they could download. What do you think? Any coding ideas? Thanks!

    • hmm I think not really much different but maybe you need a better design for that, maybe you can see iBooks iPad apps for inspiration http://www.apple.com/ipad/built-in-apps/ibooks.html

      • Mary Jane Rutkowski says:

        Thanks! I forgot about iBooks. That is really beautiful! My need is really quite simple. I have report that contains 8 separately-published chapters. I would like the reader to have the option of downloading, reading or read later (direct to Instapaper) one or more than one of the chapters. Our web site is a SharePoint site. I am still learning how to get pages (particularly with interactive content) integrated. Thanks for responding! Keep up the great work :-)

  • pau says:

    excelent!

    but if i want move the “item” in the cart toolbar just the item in all cart toolbar, in x and y. what code i move?

  • Nick says:

    Horrible… You said the only requirement was Jquery… that’s a lie. The JqueryUI library is also needed. JqueryUI adds TONS of weight to a page. We could debate what ‘TONS’ is, but i’d call JqueryUI TONS of weight for the functionality. Drag and drop functionality can be attained for 5kb. JqueryUI causes you to add the core UI library, then the Draggable addon…

    I thought this was going to be an awesome custom approach that was worthwhile. At the very least, mention JqueryUI as a requirement so people don’t waste their time thinking this doesn’t need the additional UI library.

  • John says:

    it’s good. Actually, very good. But failed in IE7.

    Could you let us know on which browser it is working fine.
    I have tested it in Opera 11.10. In opera everything is working as per the expectations. :-)

  • Alex says:

    I think this is a great example and can be implemented for a variety of uses. The only thing that I see as a bit of a down point is the decimals e.g $29.95, the total will still flash $29, can anyone recommend a tweak to fix this with this source?

  • Yann says:

    Hi,

    Really good for me.
    Is it possible to have many tabs, like shopping cart1, shopping cart2 … ?

  • Balakrishnan.S says:

    hi,
    Very useful to me thank you so much…nice stuff.

  • Gyra says:

    Solving The decimal problem:

    Replace in the Code:

    var price = parseInt($(el).parent().parent().find(“.price”).html().replace(” “, “”));

    in
    var price = parseFloat($(el).parent().parent().find(“.price”).html().replace(” “, “”));

    And

    Replace

    $(“#cprice”).html(“$ ” + total_price);

    to

    $(“#cprice”).html(“$ ” + total_price.toFixed(2));

  • raven says:

    how can it pull jquery elements to email after finished selecting items inside the cart?

  • R.D.B says:

    How can we pull a list of items from sql database?
    and then saving the selected lis back into db for future reference?

  • Art says:

    Wow – this is exactly what I am looking for! Is there any way to integrate the cart to Paypal?

  • Jean Michael says:

    how to i make your example sortable?

    when i drag item from list?

    thanks in advance…

  • Dave says:

    I like this example. I was wondering if you could and how you could incorporate Google Checkout specifically the XML API. Is there a way to send the final shopping selections to Google Checkout?

    Thanks
    Dave

  • Dave says:

    Hello,
    There are a few things I was wondering about.
    1. Is there a way to add a click function to each item that allows them to be added to the cart. (my default mobile browser on EVO 4G doesn’t support the drag feature so it wont work unless I can click something to add) I guess a solution would be to add a click feature to add or a way to display a simpler version based on the browser.

    2. Where is the check out button, can i add a Google checkout button? How could I get the info from the cart and export it to Google Checkout? Maybe XML API? how can I apply this to the theme.

    Thanks for everything
    great code
    Dave

  • Dave says:

    Opera mobile on EVO 4G does not support the drag feature either.

    Is there a way to detect a mobile device accessing the site and then supplying an alternative click to add feature?

    dave

  • Ade says:

    This is a lovely little cart and I was wondering if it will be possible then to have a checkout button take the final price straight to PayPal for payment or is there a better way of trapping and completing the buying cycle?

  • Isacco says:

    Good Job

    how I can substitute $ symbol with € euro one?

  • Mahmoud says:

    Hello, thanks for this tutorial it’s really useful. for me at least !
    i live in Minsk, Belarus and currency here is freak somehow. I’ve edit the code http://owely.com/21wFM5r and i’ve changed the currency from $ to rubl !
    my question is how can i change the total price to 250 000 instead of 250 ?
    Please help. thanks

  • shahanas mk says:

    hai,
    its really worth on my project.thanks to you

  • elang ajib says:

    I’ll try it, thanks

  • Adamantus says:

    This isn’t a tutorial because it doesn’t explain anything. I got the code to work (after downloading jquery and jquery ui, a reminder should be added), but I don’t understand any of the code.

    What’s going on here exactly? I’m just learning jquery so I don’t know what draggable and droppable are, revert, accept, drop etc have no meaning.

    His English also needs to be improved although I could understand what was written.

Leave a Comment