HTML5 Drag and Drop
HTML5 Drag and Drop
A number of events are fired during the various stages of the drag and
drop operation. But mouse events such as mousemove are not fired
during a drag operation.
The following table provides you a brief overview of all the drag and
drop events.
Event Description
ondragstart Fires when the user starts dragging an element.
ondragenter Fires when a draggable element is first moved into a drop listener.
ondragover Fires when the user drags an element over a drop listener.
ondragleave Fires when the user drags an element out of drop listener.
ondrag Fires when the user drags an element anywhere; fires constantly
but can give X and Y coordinates of the mouse cursor.
ondrop Fires when the user drops an element into a drop listener
successfully.
ondragend Fires when the drag action is complete, whether it was successful
or not. This event is not fired when dragging a file to the browser
from the desktop.
<img draggable="true">
What to Drag - ondragstart and setData()
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").
event.preventDefault()
Do the Drop - ondrop
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
Code explained: