Examples of Using the Drop Functionality: A Shopping Cart

With the help of a shopping cart, let’s examine the various possibilities of the drop functionality.

Creating a Shopping Cart with Drag-and-Drop

Let’s use drop functionality to manage a shopping cart of books. Books are displayed as images, which users can drag into a cart for purchase (Figure 10-7). Each book can be moved, and the cart is a place for depositing books. Once the book is placed in the cart, it is positioned to the right of the cart (Figure 10-8):

The shopping cart is empty

Figure 10-7. The shopping cart is empty

<script src=jquery.js></script>
<script src=jqueryui/development-bundle/ui/jquery-ui-1.8.4.custom.js></script>

<link rel=stylesheet type=text/css
      href="jqueryui/development-bundle/themes/smoothness/jquery.ui.all.css" />

<h2> Drag your books in the cart! </h2>
<div id=books>
  <img src=images/j2ee.jpg height=80 />
  <img src=images/rails.jpg height=80 />
  <img src=images/javascript.jpg height=80 />
  <img src=images/html.jpg height=80 />
</div>

<hr />

<h2> Cart: </h2>
<div id=shopping>
  <img src=images/basket.jpg class=basket />
</div>

<script>

$("div#books img").draggable ({
  revert : "invalid"
});

$("div#shopping img.basket").droppable ({
  drop : function (event, ui)
  {
    $("div#shopping").append (ui.draggable);
    $(ui.draggable).css ({ position:"relative", top:"0px", left:"0px" })
                   .draggable ("disable")
                   .css ({ opacity : 1 });
  }
});

</script>

Get jQuery UI now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.