HTML Drag and Drop API

1-3-25

In HTML, any element can be dragged and dropped.

Drag and Drop

Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.

HTML Drag and Drop Example

The example below is a simple drag and drop example:

Drag the W3Schools image into the rectangle:


It might seem complicated, but lets go through all the different parts of a drag and drop event.

Make an Element Draggable

First of all: To make an element draggable, set the draggable attribute to true:

<img draggable="true">

What to Drag - ondragstart and setDate()

Then, specify what should happen when the element is dragged.

In the example above, the ondragstart attrbute calls a function, drag(event), that specifies what data to be dragged.

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

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

In this case, the data type is "text" and the value is the id of the draggable element("drag1").

Where to Drop - ondragover

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

By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.

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

event.preventDefault()

Do the Drop - ondragover

When the dragged data is dropped, a drop event occurs.

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

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

Code explained:

More Examples

Drag and Drop

Drag the image back and forth between the two div elements.