Click here to Skip to main content
15,174,684 members
Articles / Web Development / ASP.NET
Posted 20 Feb 2009


99 bookmarked

Creating Shopping Cart UI using JQuery in an Hour

Rate me:
Please Sign up or sign in to vote.
4.91/5 (19 votes)
20 Feb 2009CPOL5 min read
In this article, we are going to demonstrate how easy it is to create a shopping cart user interface by using JQuery library.


Drag and Drop functionality serves as the main eye candy for many shopping cart applications. The shopper simply drags the item he/she is interested in the shopping cart and the shopping cart updates the total for his selected items. In this article, we are going to demonstrate how easy it is to create a shopping cart user interface by using the JQuery library. This complete interface was designed in 1 hour.

What Are We Going to Learn in this Article?

This article will focus on creating the user interface for the drag and drop scenario. This will include the list of products which will be dropped in the shopping basket. The article does not use a database at the backend to hold the items in the shopping cart, but we will show the relevant code to access the items contained in the shopping cart.

Creating the Product Entity

Let's first create the Product entity which will be responsible for holding the data related to the product.

public class Product
      public string Code { get; set;  }
      public string Name { get; set; }
      public string Description { get; set; }
      public double Price { get; set; }

The product class above looks pretty simple. The property Code is used to distinguish one product from the other.

Let's try to create some dummy products and then put them on the screen.

Populating the Products

Since we are not using any database, we will be populating the products by hand. Check out the GetProducts method below which is used to create some dummy products:

private object GetProducts()
    var products = new List<Product>
	new Product()
	{Code = "ASD123", Name = "Product 1", Description = "Product 1", Price = 12.34},
	new Product() {Code = "BBB123", 
			Name = "Product 2", Description = "Product 2", Price=15},
	new Product() {Code = "CCC123", 
			Name = "Product 3", Description = "Product 3", Price=20},
	new Product() {Code = "DDD123", 
			Name = "Product 4", Description = "Product 4", Price=12.99},
	new Product() {Code = "EEE123", 
			Name = "Product 5", Description = "Product 5", Price=14.95}

    return products;

The BindData method below populates the DataList control with the products:

private void BindData()
    var products = GetProducts();

    dlProducts.DataSource = products;

Creating the DataList Control

Let's see how to create a DataList control and populate the products into it.

<asp:DataList ID="dlProducts" RepeatColumns="3"
   RepeatDirection="Horizontal" runat="server">


   <div class="productItemStyle" price='<%# Eval("Price") %>'
   code='<%# Eval("Code") %>'  id='item_<%# Container.ItemIndex + 1 %>'>
   <%# Eval("Code") %>
   <%# Eval("Name") %>
   <%# Eval("Description") %>

   $<%# Eval("Price") %>



The DataList control contains a Div element which contains the product. For each item, a new Div item is created. The important point to notice about the Div element is the use of custom attributes "price", "code" and "id". The price denotes the price of the product. The code denotes the code for the product and the id is created dynamically using the Container.ItemIndex sequential count. This will ensure that each Div has a separate id.

When you run the above code, you will see the following result:

Image 1

NOTE: We are applying few styles on the Div element. The name of the style is "productItemStyle". You can download the complete code at the end of this article and check out the styles.

Making Products Div Draggable

The next step is to make Div draggable. This can be easily accomplished by using JQuery. But first you need to download a couple of JavaScript files.

  1. Download JQuery latest *.js file from
  2. Download JQuery UI *.js file. You can personalize the download yourself. Just select all checkboxes when personalizing your download and it will download all the features for the JQuery UI helpers.

Next, add a reference to your JQuery files as shown below:

<script language="javascript" type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script language="javascript" type="text/javascript" 

NOTE: Both the *.JS files are available in the download.

Let's make our products DIV draggable.

$(document).ready(function() {

        $(".productItemStyle").draggable({ helper: "clone", opacity: "0.5" });

We are making our element draggable inside the document.ready function. This is to ensure that the document has been loaded successfully and the DOM tree is now ready. We are referencing the product div by its class name which is "productItemStyle". The draggable function makes an item draggable. The draggable function also takes in helper which is used to clone the element and opacity which is used to indicate that the dragged item opacity is less than the original item opacity.

After writing the above code, your product div elements will automatically become draggable. Now, you can also say "Look Ma only one line of code!!".

Creating DropZone

We got our draggable item working, now let's focus on the dropZones. DropZones are areas in which you will drop your draggable item. In this demo, we will be using a single drop zone which will serve as a shopping basket.

The drop zone is nothing more than a div element which is changed into droppable using the magic of the JQuery library.

            accept: ".productItemStyle",
            hoverClass: "dropHover",
            drop: function(ev, ui) {

        // code here


At the minimum, the dropZone code will look something like the above. The accept parameter indicates that it will accept an element whose class is ".productItemStyle". The hoverClass represents the class which will be displayed when the dragged item is in focus with the dropZone. The drop function will be fired whenever the draggedItem is dropped into the dropZone.

Let's implement the drop function.

Implementation of the Drop Function

Basically, the drop function is where all the magic happens. The purpose of the drop function is to add the droppedItem to the shopping cart, add a remove link to the dropped item and update the shopping cart whenever an item is added or removed.

           accept: ".productItemStyle",
           hoverClass: "dropHover",
           drop: function(ev, ui) {

               var droppedItem = ui.draggable.clone().addClass("droppedItemStyle");

               var productCode = droppedItem[0].attributes["code"].nodeValue;
               var productPrice =

               var removeLink = document.createElement("a");
               removeLink.innerHTML = "Remove";
               removeLink.className = "deleteLink";
               removeLink.href = "#";
               removeLink.onclick = function()
                   $(".dropZone").children().remove("#" + droppedItem[0].id);
                   updateTotal(productPrice * (-1));




Remember earlier we set the code, price and id as attached properties to the Div element. Now, we can access those properties using the code below:

var productCode = droppedItem[0].attributes["code"].nodeValue;
                var productPrice = getFormattedPrice

The updateTotal is responsible for updating the running total of the shopping cart.

// update the total!
    function updateTotal(price) {

        total += parseFloat(price);


The line $(".shoppingCartTotal").effect("bounce"); is used to create a bouncy effect whenever the total is updated.

Selecting the Items from the Shopping Cart

Since we are not writing the selected items to the database, we thought it would be wise to give some code on how to access the items contained inside the shopping cart.

function listSelectedItems()
       var itemsInShoppingCart = $(".dropZone div");


The above code will alert out the code, price of the items inside the shopping cart. You can also alert out the "id" of the div in the same fashion.

Finally, check out the animation of the complete shopping cart below:

Image 2


Shopping carts user interface design is always a trivial task but now using the power of JQuery, we can easily create an attractive UI in a matter of hours. We will be building this example further in the future and adding more attractive features to the shopping cart.


  • 17th February, 2009: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.

I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

QuestionTo remove description from dropzone Pin
sijinraj11-Apr-15 7:43
Membersijinraj11-Apr-15 7:43 
Questionshopig Pin
trushdotnet3-Apr-14 23:39
Membertrushdotnet3-Apr-14 23:39 
Generalthere is a bug Pin
justin_wang24-May-10 17:12
Memberjustin_wang24-May-10 17:12 
QuestionAdd to cart link Pin
Dan Bowden24-Aug-09 5:34
MemberDan Bowden24-Aug-09 5:34 
Questionhow to change to use database's data Pin
9517534566624-Jun-09 1:26
Member9517534566624-Jun-09 1:26 
Generalgood Pin
nainpunya12-Mar-09 22:04
Membernainpunya12-Mar-09 22:04 
GeneralGood One Pin
mainreturn7-Mar-09 20:03
Membermainreturn7-Mar-09 20:03 
GeneralRe: Good One Pin
azamsharp7-Mar-09 22:42
Memberazamsharp7-Mar-09 22:42 
GeneralToo much code Pin
janblomquist123425-Feb-09 1:56
Memberjanblomquist123425-Feb-09 1:56 
GeneralRe: Too much code Pin
azamsharp25-Feb-09 5:11
Memberazamsharp25-Feb-09 5:11 
GeneralSome other JQuery shopping carts examples Pin
gstolarov23-Feb-09 4:52
Membergstolarov23-Feb-09 4:52 
GeneralRe: Some other JQuery shopping carts examples Pin
azamsharp23-Feb-09 5:13
Memberazamsharp23-Feb-09 5:13 
GeneralThis is a nice article Pin
Pete O'Hanlon22-Feb-09 12:08
mvaPete O'Hanlon22-Feb-09 12:08 
GeneralRe: This is a nice article Pin
azamsharp22-Feb-09 12:09
Memberazamsharp22-Feb-09 12:09 
GeneralNice one Azam Pin
Sacha Barber21-Feb-09 6:05
MemberSacha Barber21-Feb-09 6:05 
GeneralRe: Nice one Azam Pin
azamsharp21-Feb-09 6:15
Memberazamsharp21-Feb-09 6:15 
GeneralRe: Nice one Azam Pin
Sacha Barber21-Feb-09 6:22
MemberSacha Barber21-Feb-09 6:22 
GeneralJQuery Shopping Cart with Images and Quantity Management Support Pin
azamsharp20-Feb-09 12:03
Memberazamsharp20-Feb-09 12:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.