Easy Tutorial
❮ Html Links Html Media ❯

HTML5 Drag and Drop


Drag and drop is a part of the HTML5 standard.


Drag the tutorialpro.org icon into the rectangle.


Drag and Drop

Drag and drop is a common feature, where you grab an object and drag it to a different location.

In HTML5, drag and drop is part of the standard, and any element can be draggable.


Browser Support

Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support drag and drop.

Note: Safari 5.1.2 does not support drag and drop.


HTML5 Drag and Drop Example

The following example is a simple drag and drop example:

Example

It may seem complicated, but we can examine different parts of the drag and drop events separately.


Making Elements Draggable

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


What to Drag - ondragstart and setData()

Then, specify what happens when the element is dragged.

In the example above, the ondragstart attribute calls a function, drag(event), which specifies the data being dragged.

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

Text is a DOMString representing the type of draggable data to be added to the drag object. 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 into other elements. To allow a drop, we must prevent the default handling of the element.

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


Performing the Drop - ondrop

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

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

Code explanation:


More Examples

Drag and Drop Images Back and Forth

❮ Html Links Html Media ❯