Click here to Skip to main content
15,860,861 members
Articles / Web Development / ASP.NET

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 176.6K   5.7K   99   18
In this article, we are going to demonstrate how easy it is to create a shopping cart user interface by using JQuery library.

Introduction

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.

C#
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:

C#
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:

C#
private void BindData()
{
    var products = GetProducts();

    dlProducts.DataSource = products;
    dlProducts.DataBind();
}

Creating the DataList Control

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

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

   <ItemTemplate>

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

    <li>
   $<%# Eval("Price") %>
   </li>
   </div>

   </ItemTemplate>

   </asp:DataList>

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 www.jquery.com
  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:

JavaScript
<script language="javascript" type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script language="javascript" type="text/javascript" 
	src="jquery-ui-personalized-1.6rc4.min.js"></script>

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

Let's make our products DIV draggable.

JavaScript
$(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.

JavaScript
$(".dropZone").droppable(
        {
            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.

JavaScript
$(".dropZone").droppable(
       {
           accept: ".productItemStyle",
           hoverClass: "dropHover",
           drop: function(ev, ui) {

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

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

               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));
               }

               droppedItem[0].appendChild(removeLink);

               $(this).append(droppedItem);

               updateTotal(productPrice);
           }
       }
       );

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:

JavaScript
var productCode = droppedItem[0].attributes["code"].nodeValue;
                var productPrice = getFormattedPrice
				(droppedItem[0].attributes["price"].nodeValue);

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

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

        total += parseFloat(price);
        $("#total").html(total.toFixed(2));
        $(".shoppingCartTotal").effect("bounce");

    }

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.

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

       for(i=0;i<=itemsInShoppingCart.length-1;i++)
       {
           alert(itemsInShoppingCart[i].attributes["code"].nodeValue);
           alert(itemsInShoppingCart[i].attributes["price"].nodeValue);
       }
   }

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

Conclusion

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.

History

  • 17th February, 2009: Initial version

License

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


Written By
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, Blinds.com 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 6:43
sijinraj11-Apr-15 6:43 
Questionshopig Pin
trushdotnet3-Apr-14 22:39
trushdotnet3-Apr-14 22:39 
Generalthere is a bug Pin
justin_wang24-May-10 16:12
justin_wang24-May-10 16:12 
QuestionAdd to cart link Pin
Dan Bowden24-Aug-09 4:34
Dan Bowden24-Aug-09 4:34 
Questionhow to change to use database's data Pin
9517534566624-Jun-09 0:26
9517534566624-Jun-09 0:26 
Generalgood Pin
nainpunya12-Mar-09 21:04
nainpunya12-Mar-09 21:04 
GeneralGood One Pin
mainreturn7-Mar-09 19:03
mainreturn7-Mar-09 19:03 
GeneralRe: Good One Pin
azamsharp7-Mar-09 21:42
azamsharp7-Mar-09 21:42 
GeneralToo much code Pin
janblomquist123425-Feb-09 0:56
janblomquist123425-Feb-09 0:56 
GeneralRe: Too much code Pin
azamsharp25-Feb-09 4:11
azamsharp25-Feb-09 4:11 
GeneralSome other JQuery shopping carts examples Pin
gstolarov23-Feb-09 3:52
gstolarov23-Feb-09 3:52 
GeneralRe: Some other JQuery shopping carts examples Pin
azamsharp23-Feb-09 4:13
azamsharp23-Feb-09 4:13 
GeneralThis is a nice article Pin
Pete O'Hanlon22-Feb-09 11:08
subeditorPete O'Hanlon22-Feb-09 11:08 
GeneralRe: This is a nice article Pin
azamsharp22-Feb-09 11:09
azamsharp22-Feb-09 11:09 
GeneralNice one Azam Pin
Sacha Barber21-Feb-09 5:05
Sacha Barber21-Feb-09 5:05 
GeneralRe: Nice one Azam Pin
azamsharp21-Feb-09 5:15
azamsharp21-Feb-09 5:15 
GeneralRe: Nice one Azam Pin
Sacha Barber21-Feb-09 5:22
Sacha Barber21-Feb-09 5:22 
GeneralJQuery Shopping Cart with Images and Quantity Management Support Pin
azamsharp20-Feb-09 11:03
azamsharp20-Feb-09 11:03 
You can read part 2 of the article using the following link:

http://highoncoding.com/Articles/500_JQuery_Shopping_Cart_with_Images_and_Quantity_Management_Support.aspx[^]

Mohammad Azam
azamsharp@gmail.com
www.highoncoding.com
Houston, TEXAS

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.