jQuery: creating a shopping cart effect

How can I add items to a shopping cart? This is the first question that pops into your head when you have to create a simple shopping cart with jQuery. In this post I'll answer to this question in the simplest way possible: using the clone() method. Before digging into the details, a short note on drag-and-drop: do not use this feature, because if you do so, you'll probably make things harder for your customers. Big companies such as Amazon don't use this feature in their shopping carts, so this is a good reason for avoiding this practice.

First of all, we have the following markup structure:

<div id="wrapper">

	<ul id="products">
	
		<li><img src="jquery-shopping-cart-effect/product1.png" alt="" /></li>
		<li><img src="jquery-shopping-cart-effect/product2.png" alt="" /></li>
		<li><img src="jquery-shopping-cart-effect/product3.png" alt="" /></li>
		<li><img src="jquery-shopping-cart-effect/product4.png" alt="" /></li>
		<li><img src="jquery-shopping-cart-effect/product5.png" alt="" /></li>
		<li><img src="jquery-shopping-cart-effect/product6.png" alt="" /></li>
		<li><img src="jquery-shopping-cart-effect/product7.png" alt="" /></li>
		<li><img src="jquery-shopping-cart-effect/product8.png" alt="" /></li>
		<li><img src="jquery-shopping-cart-effect/product9.png" alt="" /></li>
		<li><img src="jquery-shopping-cart-effect/product10.png" alt="" /></li>
	
	</ul>
	
	<div id="cart">
	
		<h2>Items in the cart: <span id="qty">0</span></h2>
	
	</div>

</div>

We want to make the images appear inside the cart once clicked, plus incrementing the quantity of the items. Here's how we can do:

var Cart = new function() {

  var products = $('#products', '#wrapper');
  var cart = $('#cart', '#wrapper');
  var qty = $('#qty', '#cart');
  var items = $('li', products);
  var qtyNo = 0;
  
  this.handleCart = function() {
  
  
    items.each(function() {
    
      var product = $('img', $(this));
      
      
      product.click(function() {
      
        qtyNo++;
      
        var $clone = product.clone();
        $clone.appendTo(cart);
        qty.text(qtyNo);
      
      
      
      });
    
    
    
    });
  
  
  
  };


}();

$(function() {

  Cart.handleCart();

});

We clone each image and we append it to the cart. Also, we increment our internal counter so that we can use its value to update the quantity. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “jQuery: creating a shopping cart effect”

Leave a Reply

Note: Only a member of this blog may post a comment.