Cover by Alex MacCaw

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Drag and Drop

Drag and drop support was originally “designed” and implemented by Microsoft back in 1999 for Internet Explorer 5.0, and IE has supported it ever since. The HTML5 specification has just documented what was already there, and now Safari, Firefox, and Chrome have added support, emulating Microsoft’s implementation. However, to put it kindly, the specification is rather a mess, and it requires a fair bit of hoop-jumping to satisfy its often pointless requirements.

There are no less than seven events associated with drag and drop: dragstart, drag, dragover, dragenter, dragleave, drop, and dragend. I’ll elaborate on each in the sections below.

Even if your browser doesn’t support the HTML5 file APIs, it’s likely that you can still use the drag and drop APIs. Currently, the browser requirements are:

  • Firefox >= 3.5

  • Safari >= 3.2

  • Chrome >= 7.0

  • IE >= 6.0

  • Opera: no support

Dragging

Dragging is fairly straightforward. To make an element draggable, set its draggable attribute to true.

<div id="dragme" draggable="true">Drag me!</div>

Now we have to associate that draggable element with some data. We can do this by listening to the dragstart event and calling the event’s setData() function:

var element = $("#dragme"); element.bind("dragstart", function(event){ // We don't want to use jQuery's abstraction event = event.originalEvent; event.dataTransfer.effectAllowed = "move"; event.dataTransfer.setData("text/plain", $(this).text()); event.dataTransfer.setData("text/html", $(this).html()); event.dataTransfer.setDragImage("/images/drag.png", ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required