HTML Drag and Drop (DnD) is a powerful user interface concept. To copy, reorder, and delete items the HTML Drag and Drop is used. With the help of a mouse, we can drag an element to another location and drop the element at the desired location by releasing the mouse button. In traditional HTML4, complex JavaScript programming or other JavaScript frameworks like jQuery were used to achieve the Drag and Drop functionality.
Events for Drag and Drop feature:
Event | Uses |
Drag | Used to trigger when the mouse moves while dragging the object. |
Dragstart | Used to trigger when the dragging object starts. |
Dragenter | Used to trigger when the mouse cursor moves over the target element. |
Dragover | Used to trigger when the mouse cursor moves over an element. |
Dragleave | Used to trigger when the mouse cursor leaves an element. |
Drop | Used to trigger when the drag operation ends. |
Dragend | Used to trigger when the mouse button is released to complete the drag operation. |
Example:
<!DOCTYPE HTML> <html> <head> <style> #div1 { width: 300px; height: 100px; padding: 10px; border: 5px solid red; } </style> <script> function allowDrop(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)); } </script> </head> <body> <p>Drag the image to the rectangle:</p> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <br> <img id="drag1" src="preload.gif" draggable="true" ondragstart="drag(event)" width="200" height="80"> </body> </html>
Explanation:
In the above example, we have used the ondrop and ondragover events on div element, and ondragstart event on img tag. To see the effect drag the image to the rectangle.
Stages during Drag and Drop operations:
Make an element draggable:
Set the draggable attribute to “true” on the element, to make an element draggable.
Example:
<img draggable = “true”>
What to drag:
Use ondragstart() and setData() methods, to indicate what should happen when an element is dragged.
Where to Drop:
Use ondragover() event, to indicate where to drop an element after dragging.
Do the Drop:
Use ondrop() event to drop an element.
Supporting Browsers:
Chrome, IE, Firefox, Opera, and Safari.