Drag & drop is an amazing and handy feature that can be used to make the website more interactive and effective for users. With it, we can drag any item on the screen and drop it anywhere.

We can convert any HTML element into the drag element.

Browser Support for drag-and-drop

The numbers in the table represents the first version of the browser that fully supports Drag-and-Drop.

Drag-and-Drop browser support

API

Google Chrome

IE

Firefox

Safari

Opera Mini

Drag and Drop

4.0

9.0

3.5

6.0

12.0

HTML Drag and Drop Example

The example below is a simple drag & drop 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>

You might find it complicated, but let us go through all the different parts of a drag & drop function.

Make an Element Draggable

To make an element draggable, you need to set the draggable attribute to true:

<img draggable="true">

What to Drag - ondragstart and setData()

Now we have to specify, what should happen when dragging the element.

In the example that is specified above, the ondragstart attribute calls the drag(event) function which specifies what data to be dragged.

The dataTransfer.setData() function sets the type of data to be dragged and its value:

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

In this case, we set the data type as "text" and the value of the draggable data is its id ("drag1").

Where to Drop - ondragover

The ondragover event specifies the area where data can be dropped.

By default, draggable data cannot be dropped in other elements. We must prevent the default handling of the element in order to allow a drop.

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

event.preventDefault()

Do the Drop - ondrop

When the data is dropped, a drop event occurs.

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

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

Code explained:

  • Call preventDefault() : It prevents the browser default handling of the data
  • dataTransfer.getData() : This method returns any data that was set to the same type in the setdata() method.
  • The dragged data will be the id of the dragged element ("drag1")
  • Append the drop element into the dragged element. 

Live example: