HTML5 Drag and Drop (Drag and Drop) is a part of the HTML5 standard.
Drag and Drop (Drag and drop) is a common feature, which involves grabbing an object and dragging it to another location.
willexample.comDrag icons into a rectangular box.
Drag and Drop
Dragging is a common feature, allowing objects to be grabbed and dragged to another location.
In HTML5, dragging is a standard feature, allowing any element to be dragged.
Browser Support
![]()
![]()
![]()
![]()
![]()
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support dragging.
Note:Safari 5.1.2 does not support dragging.
HTML5 Drag and Drop Example
The following example is a simple drag and drop example:
Example
Try it »
It may look complicated, but we can study the different parts of the drag and drop events separately.
Set the element to be 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 being dragged.
In the above example, 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:
{
ev.dataTransfer.setData("Text",ev.target.id);
}
Text represents the type of data to be added to the dragged object. The value is the id of the draggable element ("drag1").
Where to drop - ondragover
The ondragover event specifies where the dragged data should be placed.
By default, data or elements cannot be placed into other elements. To allow placing, we must prevent the default handling of the element.
This is done by calling the event.preventDefault() method of the ondragover event:
Drop - ondrop
When dropping the dragged data, the drop event occurs.
In the above example, the ondrop attribute calls a function, drop(event):
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
Code explanation:
- Calling preventDefault() to avoid the browser's default handling of the data (the default behavior of the drop event is to open the link).
- Using the dataTransfer.getData("Text") method to retrieve the dragged data. This method returns any data of the same type that was set in the setData() method.
- The dragged data is the id of the dragged element ("drag1").
- Append the dragged element to the target element (the drop target).
More Examples
Dragging back and forth images
How to drag images between two <div> elements.