Drag ‘n’ Drop Shopping Cart With jQuery UI (Tutorial)

Drag ‘n’ dropping items has its various popular uses and shopping carts are definitely one of them.

In this tutorial, we’ll be creating a simple shopping cart that works with drag ‘n’ drops.

It will have support for add-to-basket with quantity updates (so that the same items could be added more than once) and removing items from the basket. It will be totally client-side and cover the basic functionality (no PayPal integration, etc.).

For that, we’ll be using, probably the best drag-drop library, jQuery UI Draggable/Droppable in this tutorial. Here is the end result:

Demo
Download

Let’s get started:

Step 1 -> Get the custom jQuery UI package

jQuery UI Custom Download

jQuery UI has lots of features and every feature adds bytes to its source, it is much more smarter to get only what we need.

As you can see from the screenshot above, we need the Core, Widget, Mouse from the core and Draggable + Droppable from the interactions.

jQuery UI Custom Download Size

This will end up in a 37kb JavaScript file which is not so bad for the features and compatibility offered.

Step 2 -> Insert the JS files into the web page

Let’s make sure we have the jQuery and jQuery UI inserted in the web page. Just add these lines inside the <head></head> tags.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="jquery-ui-1.9.0.custom.min.js"></script>

Step 3 -> The HTML for the products

Let’s use a simple unordered list structure for featuring the products:


<section id="product">
    <ul class="clear">
        <li data-id="1">
            <a href="#">
                <img src="http://lorempixel.com/150/100/technics/1/" alt="">
                <h3>Product name</h3>
                <p>Product detail</p>
            </a>
        </li>
        <li data-id="2">...</li>
        <li data-id="3">...</li>
    </ul>
</section>

Step 4 -> The HTML for the basket

And a basic structure for the basket:


<aside id="sidebar">
    <div class="basket">
        <div class="basket_list">
            <div class="head">
                <span class="name">Product name</span>
                <span class="count">Quantity</span>
            </div>
            <ul>
            </ul>
        </div>
    </div>
</aside>

Step 5 -> Let’s start dragging

As you already know we’ll be using the jQuery UI Draggable and Droppable:


// jQuery UI Draggable
$("#product li").draggable({

    // brings the item back to its place when dragging is over
    revert:true,

    // once the dragging starts, we decrease the opactiy of other items
    // Appending a class as we do that with CSS
    drag:function () {
        $(this).addClass("active");
        $(this).closest("#product").addClass("active");
    },

    // removing the CSS classes once dragging is over.
    stop:function () {
        $(this).removeClass("active").closest("#product").removeClass("active");
    }
});

Step 6 -> And, time for dropping

The item will be dropped elegantly, thanks to the jQuery UI Droppable:


// jQuery UI Droppable
$(".basket").droppable({

    // The class that will be appended to the to-be-dropped-element (basket)
    activeClass:"active",

    // The class that will be appended once we are hovering the to-be-dropped-element (basket)
    hoverClass:"hover",

    // The acceptance of the item once it touches the to-be-dropped-element basket
    // For different values http://api.jqueryui.com/droppable/#option-tolerance
    tolerance:"touch",
    drop:function (event, ui) {

        var basket = $(this),
                move = ui.draggable,
                itemId = basket.find("ul li[data-id='" + move.attr("data-id") + "']");

        // To increase the value by +1 if the same item is already in the basket
        if (itemId.html() != null) {
            itemId.find("input").val(parseInt(itemId.find("input").val()) + 1);
        }
        else {
            // Add the dragged item to the basket
            addBasket(basket, move);

            // Updating the quantity by +1" rather than adding it to the basket
            move.find("input").val(parseInt(move.find("input").val()) + 1);
        }
    }
});

Step 7 -> Adding the dropped item to the basket

We are no wadding the item to the basket with any details it has:


function addBasket(basket, move) {
    basket.find("ul").append('<li data-id="' + move.attr("data-id") + '">'
            + '<span class="name">' + move.find("h3").html() + '</span>'
            + '<input class="count" value="1" type="text">'
            + '<button class="delete">✕</button>');
}

Step 8 -> Deleting an item for the basket

A simple way to remove items from the basket:


$(".basket ul li button.delete").live("click", function () {
    $(this).closest("li").remove();
});

And, it is that easy. Hope this tutorial helps you creating your own shopping cart.

  • Vasco

    Pretty slick. Thx for the tut.

  • Augusto Carvalho dos Santos

    Very nice tutorial !
    I wanna know if it´s possible to block more than one product ? Just one quantity of the product in the basket. Thank´s a lot

  • @Augusto,

    Yes, you can do that. You should simply be checking the amount of the same item in the basket with the “drop” event. If it exists, don’t update the basket..

  • Andre

    Hi there! Nice tutorial.
    I have changed a little bit to use several baskets, but I can’t do one thing and I would like some help.
    I got to disable the product from product list once I drop it into the basket, but I can’t get it back to product list when I remove it from the basket.
    Can you help me?

  • Daniel L.

    Excellent tutorial. However, when I tried viewing the demo with IE8 (and IE7), it doesn’t seem to work. Not sure if it’s because of the CSS or JS.

  • Mehdi

    Thanks for this nice work.
    It’s not working with IE8 !

  • m_s

    can i use this with php?
    How do i pass the values in the basket (cart) to a php to process?

  • Theo

    Nice and simple!!! For IE8 and IE7 funs… Play a bit with the CSS and will work.
    I have thought the same question with m_s. How can I connect the cart with a PHP script?
    Thanks

  • steve

    How do you process the products once in the cart, ie checkout?

  • Naveen

    @ Theo,

    Can you tell us what css changes you did for IE 7 and IE8.

  • vikash

    I want to stop basket items when i refresh the page bcoz it’s deleted when i refresh the page.

  • Ramana

    Very nice tutorial,Thank you

  • ramana

    Can you tell us what css changes you did for IE 7 and IE8.

  • Ramana

    This is not working in ie7 and ie8.Can you please provide solution for this

  • Nice tutorial

  • the live() event handler is deprecated, the delete from cart function can use the on() event handler instead attached to the body and delegated to the button.delete like so:

    $(‘body’).on(“click”, ‘button.delete’, function (event) {
    $(this).closest(‘li’).remove();
    });

  • sagar

    how to implement in asp.net website, means what is the next step(check out) after that. how i get drop product in my process page

  • In IE8, this script is not adding the product to Cart. Can u suggest what changes require there……………Please its really Urgent 🙂

  • John

    Great work.

    How to save it to a SQL database?Thanks.

  • Good stuff. Checked out the demo, seems promising but -ve point is that it doesn’t support IE 7 and IE 8.

Search