Tutorials
THE WORLD'S LARGEST WEB DEVELOPER SITE

HTML5 Drag and Drop

Drag and Drop

 

Drag and drop is known to be a very common feature. It happens when you are "grabbing" an object and dragging it to a someother location.

In the latest HTML5, drag and drop is included, and any element is draggable.

Browser Support

 

The table numbers specifies the first browser version which fully supported Drag and Drop.

API
Drag and Drop 4.0 9.0 3.5 6.0 12.0

HTML Drag and Drop Example

 

The example given below illustrates a simple drag and drop scenario:

Example

<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<img id="drag1" src="img_logo.gif" draggable="true"
ondragstart="drag(event)" width="336" height="69"
>


</body>
</html>
Try it Yourself

It may look complicated, but after going through all the parts of a drag and drop event we can understand it clearly.

Make an Element Draggable

 

First: For making an element draggable, you need to change the draggable attribute to true:

Example

<img draggable="true">

What to Drag - ondragstart and setData()

 

Later,you need to specify what should be happening if the element is dragged.

In the example given above, the ondragstart attribute is calling a function, drag(event), which is specifying what data should be dragged.

The dataTransfer.setData() method is setting the data type and the value of the dragged data:

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

Here, the data type is given as "text" and the value given is the draggable element id ("drag1").

Where to Drop - ondragover

 

The ondragover event is used to specify where the dragged data should be dropped.

With default settings, data/elements is not possible to be dropped in some other elements. For allowing a drop, we must be preventing the default handling of the element.

This can be done by calling the event.preventDefault() method for the ondragover event:

event.preventDefault()

Do the Drop - ondrop

 

When the dragged data is getting dropped, a drop event is occuring.

In the above example, the ondrop attribute is calling a function, drop(event):

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}

Code explained: