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.
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;
dlProducts.DataBind();
}
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">
<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:
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.
- Download
JQuery
latest *.js file from www.jquery.com
- 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"
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.
$(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 dropZone
s. DropZone
s 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.
$(".dropZone").droppable(
{
accept: ".productItemStyle",
hoverClass: "dropHover",
drop: function(ev, ui) {
}
}
);
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.
$(".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:
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.
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.
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:
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