# Implementing HTML5 Drag and Drop

One of the new features in HTML5 is native drag and drop. Surprisingly, Internet Explorer has had support for native drag and drop since version 5.5; in fact, the HTML5 implementation is based on IE's support. In today's tutorial, we'll look at how to implement native drag and drop to build a simple shopping cart interface.

## Step 0. What We're Doing

Here's what we're going to build: it's a basic shopping cart with a product panel and a cart panel. To "purchase" a product, you'll be able to drag it from the panel to the cart; we'll keep a track of quantity and remove items from the product panel when they're out of stock.

Note that we're not actually building a shopping cart here; we won't be working with any server-side goodness today. This is just the front-end; the point is HTML5 drag and drop.

## Step 1. The HTML

 1   2   3   4   5   6  Drag and Drop Shopping Cart  7   8   9   10   11   12   13   14   15  

Pretty basic: we're linking to a stylesheet and jQuery; we're only using jQuery for easy event handling and DOM manipulation; the drag and drop will be native. However, we're up against a wall here, because HTML5 drag and drop adds a few properties to the event object. JQuery doesn't use the default event object; it creates its own to equalize event object issues. Because of this, we don't get the special properties with jQuery's event object. But don't worry; there's a plugin for that; we're pulling in the Native Drag and Drop to make it all work. Finally, we'll include our script: dragdrop.js.

Now we're ready to add in our product list; for product images, I'm using icons from the Apple Icon Superpack, created by SvenVath. (I have renamed the icons with simpler names and resized them to 180px.)

Add ul#products as the first child inside the body. Once you've done that, we'll examine the first list item:

We've got out list item, with an anchor inside; notice that each anchor item will have a class of item (important when we get to the CSS) and a custom id (important when we get to the JavaScript). Then, the anchor also has the draggable="true" attribute; this should be all we need to make the element draggable (we'll see a few caveats soon). We're using an anchor tag here so you could do something for browsers without native drag and drop support (although we won't be doing that here). Then we have the product image and a div with the product info. And yes, it's necessary to wrap the price and quantity with span

Here are the rest of the list items:

 1   2 
•  3   4 
 5 

iPhone

 6 

Price: $199.00  7  Quantity: 16  8   9  •  10  •  11   12   13  AppleTV  14  Price:$299.00

 15 

Quantity: 9

 16 
 17 
•  18 
•  19   20 
 21 

Cinema Display

 22 

Price: $899.00  23  Quantity: 4  24   25  •  26  •  27   28   29  iPod Nano  30  Price:$149.00

 31 

Quantity: 20

 32 
 33 
•  34 
•  35   36 
 37 

Macbook

 38 

Price: $1199.00  39  Quantity: 13  40   41  •  42  •  43   44   45  Mac Mini  46  Price:$599.00

 47 

Quantity: 18

 48 
 49 
• 

There's one final piece of HTML: the shopping cart:

 1   2 
 3 

Shopping Cart

 4 
 5 

Total: 0.00  6  Drop here to add to cart  7   And that's our HTML! ## Full Screencast ## Step 2. The CSS Ideally, all you should need to do to make an element draggable is set that draggable attribute to true; however, there's more to it. To get things working properly, you have to set a few things in CSS. First, think of this: what does clicking and dragging do on "normal" (undraggable) element? Usually, it selects text. Then, we want to make sure we're dragging the element, and not just its contents. To deal with with, need to use the following CSS:  1   2 [draggable=true] {  3  -moz-user-select:none;  4  -webkit-user-select: none;  5  -webkit-user-drag: element;  6 }  For our convenience, the native drag and drop plugin we're using sets these properties for us, so we can leave them out if we want. However, we will do this:  1   2 [draggable=true] {  3  cursor : move;  4 }  Let's start styling:  1   2 html {  3  height:100%;  4 }  5 body {  6  background: #ececec;  7  margin:0;  8  padding:0;  9  font: 13px/1.5 helvetica, arial, san-serif;  10  height: 100%;  11 }  12 h1, h2 { text-align:center; }  13 h2 {  14  position:absolute;  15  bottom: 20px;  16  color:#fff;  17  text-shadow:0 0 10px rgba(0, 0, 0, 0.75);  18  display:none;  19 }  20 p { margin:0; }  Since we're not using a full reset, here's our pseudo-reset. It should all be pretty self-explanetory. We're setting the height to 100% on the html and body elements because we want #cart to be the entire height of the screen; to do that, every parent element needs to have its height set to 100%. Also, notice that we're using rgba to set the shadow color; if a browser doesn't support this, there won't be a shadow on the h2. And, we're hiding this h2 by setting display: none. Remember, the h2 says "Drop here to add to cart," so we'll have it fade in when the drag starts and fade out when the drag ends. Moving on to our products list . . .  1   2 #products {  3  float:left;  4  list-style:none;  5  width:65%;  6  padding:0;  7 }  8 #products li {  9  display:inline;  10 }  Again, pretty obvious. The important thing in this snippet is that the list items will be displayed inline. Since we'll set display:block; float:left  on the anchors, IE will give the list items a "stair-steps" effect; we can work around this bug by setting display: inline on the anchor's parent element. Speaking of the anchors, let's style them next.  1   2 .item {  3  display:block;  4  float:left;  5  width:180px;  6  height:180px;  7  margin:10px;  8  border:1px solid #494949;  9  text-align:center;  10  text-decoration:none;  11  color: #000;  12  overflow:hidden;  13 }  14 .item img {  15  border:0;  16  margin:10px auto;  17  width:160px;  18  height:160px;  19 }  20 .item div {  21  background:rgb(0, 0, 0);  22  background: rgba(0, 0, 0, 0.5);  23  position:relative;  24  bottom:69px;  25  color:#f3f3f3;  26  padding:5px 0;  27  display:none;  28 }  Each anchor will be styled as a 180x180px box; this will be filled with the product image. The product info div will be positioned over the image, at the bottom of the square. Notice we have to set a background color and then reset it for modern browsers, because IE doesn't support RGBa. We're setting display:none  on this info div so we can fade it in and out when the "customer" hovers on and off, respectively. All that's left to style is the shopping cart; we'll look at it here, but, remember, the list items will be inserted by jQuery later on, so you won't see this taking place just yet.  1   2 #cart {  3  float:right;  4  background-color:#ccc;  5  width:25%;  6  padding:0 5%;  7  height:100%;  8 }  9 #cart ul {  10  padding:0;  11 }  12 #cart li {  13  list-style:none;  14  border-bottom:1px solid #494949;  15  padding:5px;  16 }  17 #cart .quantity {  18  font-weight:bold;  19  padding-right:10px;  20  margin-right:10px;  21  border-right:1px solid #494949;  22  display:inline-block;  23  width:15px;  24  text-align:right;  25 }  26 #cart .price {  27  float:right;  28 }  29 #total {  30  float:right;  31 }  Elements with the classes quantity and price will be within the dynamically inserted list items. That's it for CSS; before moving on to the star of this show, let's look at our work so far. ## Step 3. The JavaScript We've made it to the JavaScript; according to the the HTML5 doctor: HTML 5 DnD is based on Microsoft’s original implementation which was available as early as Internet Explorer 5! Now currently supported in IE, Firefox 3.5 and Safari 4. Here's a list of the events that HTML5 drag and drop offers: • drag • dragstart • dragover • dragenter • dragleave • dragend • drop We won't use all of these, but we'll see how they most of them work. First, we'll work with our products:  1   2 ('.item')  3  .bind('dragstart', function (evt) {  4  evt.dataTransfer.setData('text', this.id);  5  $('h2').fadeIn('fast');  6  })  7  .hover(  8  function () {$('div', this).fadeIn(); },  9  function () { $('div', this).fadeOut(); }  10  );  We start by grabbing all the items; then, we bind a funciton to the dragstart event; this event will fire when we start dragging the event. The first thing we'll do when an object is dragged is set some data; actually, if no data is set, firefox won't let the element drag. Special to drag events is a object property on the event object called dataTransfer; we'll be using two methods of this property: setData and getData. Here, we're using the setData method, which takes two parameters: a data format and the data. We'll use the datatype 'text.' Then, we'll set the data to be the id of the element the user is dragging. Then, we'll fade in the h2 as an prompt to the customer. We also use the jQuery hover method to fade in the product info when we mouseover and fade it out when we mouseout. Notice that we pass the node we're hovering over as context, so we only get the div of the appropriate product. Now let's add the event handlers to the #cart. We're going to act on the dragover, dragenter, and drop events:  1   2 $('#cart')  3  .bind('dragover', function (evt) {  4  evt.preventDefault();  5  })  6  .bind('dragenter', function (evt) {  7  evt.preventDefault();  8  })  9  .bind('drop', function (evt) {  10   11  }); 

To get the drop event to fire, we need to cancel the default action on the dragover event; this event fires continuously on the drop target when a draggable element is dragged over it. For IE only, we need to cancel the default action on the dragenter event, which occurs only when the draggable element enters the drop target. The reasons behind cancelling the default action are somewhat foggy; to be honest, I don't really understand them. Here's what Remy Sharp says about it:

What it’s telling the browser is that this element is the one we want to catch the drag event against, otherwise the browser goes ahead does it’s normal drag action. So by cancelling the event, it tells the browser that this is the element that should start moving.

I should note that jQuery is helping us out a bit here; normally, we'd also have to return false it get it working in IE; however, jQuery's fixed preventDefault does that for us.

Now the drop event; this event, too, is fired on the drop target, which is div#cart in our case. Before we look at the function, let's talk about what this function is supposed to do:

• get the product we've dropped
• if the product has already been bought, add one to the quantity purchased; otherwise, add the item to the cart
• decrement the product quantity
• update the total price

Here's the first part:

 1   2 var id = evt.dataTransfer.getData('text'),  3  item = $('#' + id),  4  cartList =$("#cart ul"),  5  total = $("#total span"),  6  price =$('p:eq(1) span', item).text(),  7  prevCartItem = null,  8  notInCart = (function () {  9  var lis = $('li', cartList),  10  len = lis.length,  11  i;  12   13  for (i = 0; i < len; i++ ) {  14  var temp =$(lis[i]);  15  if (temp.data("id") === id) {  16  prevCartItem = temp;  17  return false;  18  }  19  }  20  return true;  21  } ()),  22  quantLeftEl, quantBoughtEl, quantLeft; 

I know; it's a lot of variables, but we'll use them all. Let's go over them; first, we get the text data that we transferred with the event; we transferred the id like this because there's nothing in the event object to tell us which element was dropped onto our target; we'll get the id and then use it to find the element that was dropped. Next, we get the cart list and the total price span. Then, we'll get the price of the individual item; we know that it's the span within the second paragraph of the item, so we can use the item as the context parameter. We'll set prevCartItem to null for now, but we'll use it to see if the item dragged into the cart is already there. The value of notInCart is a self-invoking anonymous function; it will loop over each list item in the cartList (again, we're using the context parameter) and check to see if the data property id is the same as the variable id. To understand this, you'll have to know that when we add list items to the shopping cart, we'll use the jQuery data method to set store product id with the item. In this function, we're checking for a list item with the right data; if we find one, the item is already in the cart, and so we set notInCart to false; if it isn't in the cart, we'll set the variable to true. Finally, we'll use quantLeftEl, quantBoughtEl, and quantLeft when updating quantities.

Now, for some action:

 1   2 $("h2").fadeOut('fast');  3   4 if (notInCart) {  5  prevCartItem =$('
• ', {  6  text : $('p:first', item).text(),  7  data : { id : id }  8  }).prepend($('', {  9  'class' : 'quantity',  10  text : '0'  11  })).prepend($('', {  12  'class' : 'price',  13  text : price  14  })).appendTo(cartList);  15 }  • First, we'll fade out the h2 prompt. Then, if the item isn't in the cart, we'll add it to the cart. To do this, we'll create a list item; then, we can pass an object literal as the second parameter to set properties of our new list item. We'll set the text to the product name; that comes from the first paragraph in the product item. Then, we set the data we talked about above. Next, we'll prepend a span to this list item; we'll give it a class of 'quantity' (don't forget to put class in quotes, since it's a reserved word) and set the text to zero; yes, I know it should be one, since they've just put the item in the cart, but we'll increment that later . . . and you'll see why. We'll prepend another span to the list item, this time for the price. We're going to float the price to the right, so it would seem logical to append it; but that would cause a float bug in IE; the span would actaully float right and below the list item. Finally, we'll append the list item to the shopping cart list. The last piece of this function will run whether or not the item is already in the cart or not:  1   2 quantLeftEl =$('p:last span', item);  3 quantLeft = parseInt(quantLeftEl.text(), 10) - 1;  4 quantLeftEl.text(quantLeft);  5 quantBoughtEl = $('.quantity', prevCartItem);  6 quantBoughtEl.text(parseInt(quantBoughtEl.text(), 10) + 1);  7   8 if (quantLeft === 0) {  9  item.fadeOut('fast').remove();  10 }  11   12 total.text((parseFloat(total.text(), 10) + parseFloat(price.split('$')[1])).toFixed(2));  13   14 evt.stopPropagation();  15 return false; 

First we'll get the quantity from the product item; this is the quantity left when the customer dragged the item to the cart; we'll then get the quantity that's really left; but that's a string, so we use the native function parseInt to convert it to a number (use 10 as the radix to assure that we get a decimal number) and subtract one from it. Then we reset the quantity, using jQuery's text method.

Next, we get the quantity the user has bought; this is the element with a class of 'quantity'; we use the prevCartItem as the context; this works because if the item was already in the cart, prevCartItem was set in that anonymous function; if it wasn't in the cart, we set it when we created the cart entry. We can then set the text value by getting the current value, converting to to a number, and adding one to it.

What happens when the quantity left hits zero? If it's zero, we'll fade the item out and remove it.

Finally, we have to update the total price. We've got the total span, so we can just reset the text; what we're doing is getting the current text, converting it to a number (this time we're using parseFloat to keep the cents), splitting the dollar sign off the price and converting that to a number and adding to two values. Finally, we'll use toFixed to make sure we're always showing the correct cents value.

Lastly, we don't want the drop drop event to bubble, so we'll stop its propagation and return false;

## Step 4. The Completed Project

Good job, we're finished; here's a shot of our cart in action:

If you want to check out what the other drag and drop events do, add this to the script:

 1   2 $('#cart').bind('dragleave', function (evt) {  3  console.log('dragleave');  4 });  5   6 $('.item')  7  .bind('dragend', function (evt) {  8  console.log('dragend');  9  })  10  .bind('dragstart', function (evt) {  11  console.log('dragstart');  12  })  13  .bind('drag', function (evt) {  14  console.log('drag');  15  }); 

While native HTML5 drag and drop may not be completely ready for prime time just yet (Opera doesn't support it), it's definitely exciting to see where things are going!