HTML5 Native Drag n Drop

Recently I had my first forray into creating a small drag and drop web app. Just wanted to jot down a few notes that might speed up the learning curve. Lessons learned, if you will.

Javascript API

  • dragstart
  • dragenter
  • dragover
  • dragleave
  • drop
  • dragend

These are pretty self explanatory, triggered appropriately upon the user's interaction. The only markup needed is the attribute draggable=true applied to the element(s) you want to drag.

Here is an example markup:

<div class="box" draggable=true></div>
<div class="box" draggable=true></div>
<div class="box" draggable=true></div>

<div class"drop-zone">Drop Boxes Here</div>

Pretty simple, right?

Get/Set Data

The API provides an event property, dataTransfer. This allows you to call setData() and getData() methods. This makes it very convenient to transfer data as objects are being dragged and dropped.

jQuery

Using jQuery? A quick search will show the above easy enough. Note: remember that when using jQuery, it wraps event objects with it's own event object. So if you have the following jQuery:

$('.box').on('dragstart', function (event) {
	// can't directly access event.dataTransfer object
    // must use event.originalEvent.dataTransfer
});

When using jQuery, to access the original javascript event object, you must use originalEvent.

Browser's

Finally, a few notes on browser compatibility. Safari and Firefox have particular oddities.

  • Safari needs the following css applied to allow for dragging:

    [draggable=true] {
    -khtml-user-drag: element;
    }

  • Firefox requires that data be set on dragstart. In other words, you must call event.dataTransfer.setData() when you start dragging an element. If you're not getting or setting data for any other reason, then you can easily just do something like event.dataTransfer.setData('data', 1).

Summary

That's about it. The rest is up to you to be creative. While this feature has been around for quite some time, I've yet to see it widely used - natively, that is. Or, maybe I just need to browse the web some more. Hope this helps!