HTML5 Tips and Tricks: Drag and Drop

A useful feature in HTML5 is native browser support for drag and drop (DnD). HMTL5 drag and drop supports the designation of any element as draggable, as well as setting any element as a drop target, specifying the behavior for each step along the way. Additionally, drag and drop across browser windows and even to and from the desktop is supported. Drag and Drop is natively supported by all major browsers, and partially supported as far back as IE5.

By default, only images and hyperlinks are draggable. To allow other elements to be dragged, simply declare an attribute draggable and set to true. This will allow the user to drag the element and causes the drag events (dragStart, dragEnd, and drag) and drop events (dragEnter, dragOver, dragLeave, and drop) to fire. Elements can be set to copy their content, move completely, or simply link back to the source element. An important note is that elements are not eligible drop targets by default, and so the default behavior of the dragOver and dragEnter events must be cancelled to allow dropping. A simple example of HTML5 drag and drop is given in Figure 1.

<div draggable="true" id="dragBox">
<div id="dropBox"></div>
<script type="text/javascript">// <![CDATA[
var drag = document.querySelector("#dragBox");

addEvent(drag, "dragstart", function (e) {
    // required for non-text, non-image objects otherwise doesn't work
    e.dataTransfer.setData("Text", "data value as text");  

var drop = document.querySelector("#dropBox");
addEvent(drop, "dragover", cancel);   // Tells the browser that we *can* drop on this target
addEvent(drop, "dragenter", cancel);  // Tells the browser that we *can* drop on this target

addEvent(drop, "drop", function (e) {
    if (e.preventDefault)  
        e.preventDefault();  // stops the browser from redirecting off to the text.
    this.innerHTML += "

+ e.dataTransfer.getData("Text") + "

    return false;

function cancel(e) {
    if (e.preventDefault)  
    return false;
// ]]></script>

Figure 1 Simple example of drag and drop.

Some critics call the system cumbersome because of the number of event and event handlers involved, especially since the API is based on an older IE5 implementation. However, native cross browser support of drag and drop without relying on external libraries is a useful feature that developers should be aware of, especially with the inclusion of support for file drag and drop to and from the desktop.

Further Reading


Leave a Reply

Your email address will not be published. Required fields are marked *