HTML Tutorial | HTML5 API | Drag and Drop
Drag and Drop API
The drag and drop API lets users freely drag elements inside a web page. Before HTML5, implementing this kind of feature required a large amount of complex script. In HTML5, drag and drop became part of the standard recommendation and can be used more easily. Current major web browsers all support this feature, so every element in a web page can be dragged.
The major web browser versions that support the drag and drop API are as follows.
| API | ie | chrome | firefox | safari | opera |
|---|---|---|---|---|---|
| Drag and Drop | 9.0 | 4.0 | 3.5 | 6.0 | 12.0 |
Drag and Drop Events
When an object is dragged with the mouse and then dropped, several events occur sequentially.
The following table shows the events that occur during drag and drop in order.
| Event | Description |
|---|---|
| dragstart | Occurs when the user starts dragging an object. |
| dragenter | Occurs when the mouse first enters over the target object. |
| dragover | Occurs while dragging when the mouse is positioned over the target object. |
| drag | Occurs when the mouse moves while dragging the target object. |
| drop | Occurs on the object located where the dragged object is dropped. |
| dragleave | Occurs when dragging ends and the mouse leaves the target object. |
| dragend | Occurs the moment the mouse button is released after dragging the target object. |
All event listener methods for drag and drop events return a DataTransfer object.
The returned DataTransfer object contains information about the drag and drop operation.
draggable Attribute
Every element in a web page can be converted into a draggable object by using the draggable attribute.
ondragstart Attribute
After creating a draggable object, call the setData() method of the DataTransfer object through the ondragstart attribute.
The setData() method sets the data and data type of the object being dragged.
ondragover Attribute
The ondragover attribute sets which element the dragged target object can be placed over.
By default, an HTML element cannot be placed on top of another element.
Therefore, to allow it to be placed over another element, the default behavior of the element at the drop location must be prevented.
This can be configured simply by calling the event.preventDefault() method.
ondrop Attribute
When the dragged object is dropped, a drop event occurs.
The ondrop attribute can be used to configure the behavior for the drop event.
Example
function dragEnter(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));
}