Today many of the shopping websites have the drag drop shopping cart facility.
The drag drop of items to the cart is a easy to use and quick way of shopping.
In this article we will learn to build a drag drop shopping cart using jQuery and Knockout.
Steps to build the drag drop shopping cart
Knockout ViewModel
Create a knockout viewmodel to get the products data and store the shopping cart data. Populate the products data using a ajax call. Below code gets the data from a sample txt file in json format.
1 2 3 4 5 6 7 8 |
$.getJSON("productsData.txt", function (data) { viewModel.shoppingCartArray = ko.observableArray(); viewModel.products = ko.mapping.fromJS(data); viewModel.removeProduct = function(data){ viewModel.shoppingCartArray.remove(data); }; ko.applyBindings(viewModel); }); |
Display the list of products
Once the products are populated, display them to the user using the knockout databinding.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<div id="products"> <ul class="productList" data-bind="foreach: products"> <li> <a href="#" class="product"> <img data-bind="attr:{src: image}" /> <div> <p data-bind="text:name"></p> <p data-bind="text:'$ '+price()"></p> </div> </a> </li> </ul> </div> |
Create Shopping cart
Create a shopping cart div and using the knockout databind. This will ensure that any data added to the cart will automatically bind to the shopping cart array in viewmodel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<div class="shoppingCart" id="shoppingCart"> <h2>Shopping Cart</h2> <div class="placeholder"></div> <table> <thead> <tr> <th width="50px"> </th> <th width="100px">Name</th> <th width="100px">Price</th> </tr> </thead> <tbody data-bind="foreach:shoppingCartArray"> <tr> <td width="100px"><a href="#" data-bind="click: $parent.removeProduct">Remove</a></td> <td width="100px" data-bind="text:name"></td> <td width="100px" data-bind="text:price"></td> </tr> </tbody> </table> </div> |
Enabling Drag
1 2 3 4 |
$( "#products li" ).draggable({ appendTo: "body", helper: "clone" }); |
Enabling Drop
1 2 3 4 5 6 7 8 9 10 |
$( "#shoppingCart" ).droppable({ activeClass: "ui-state-default", hoverClass: "ui-state-hover", accept: ":not(.ui-sortable-helper)", drop: function( event, ui ) { var name = ui.draggable.find('p:eq(0)').html(); var price = ui.draggable.find('p:eq(1)').html(); addToShoppingCart(name,price); } }); |
Populating the shopping cart using knockout
1 2 3 4 5 6 |
function addToShoppingCart(name,price){ viewModel.shoppingCartArray.push({ name:name, price:price }); }; |
Removing products from cart
1 2 3 |
viewModel.removeProduct = function(data){ viewModel.shoppingCartArray.remove(data); }; |
And your Drag Drop Shopping cart is ready.