HTML Drag and Drop, also known as DnD, is a functionality introduced in HTML5. This feature enables users to manipulate items by copying, reordering, and deleting them using mouse interactions. By clicking and dragging an element to a different location, users can rearrange items. Releasing the mouse button will drop the element in the new location.
To enable Drag and Drop functionality in classic HTML4, you will need to resort to intricate JavaScript coding or utilize JavaScript libraries such as jQuery, among others.
Events for Drag and Drop feature
| Event | Description |
|---|---|
Drag |
It fires every time when the mouse is moved while the object is being dragged. |
| Dragstart | It is a very initial stage. It fires when the user starts dragging object. |
| Dragenter | It fires when the user moves his/her mouse cursur over the target element. |
| Dragover | This event is fired when the mouse moves over an element. |
| Dragleave | This event is fired when the mouse leaves an element. |
Drop |
Drop It fires at the end of the drag operation. |
| Dragend | It fires when user releases the mouse button to complete the drag operation. |
HTML5 Drag and Drop Example
Let's explore an illustration showcasing the drag and drop functionality in HTML 5.
To understand this example, you must have the knowledge of JavaScript.
<script>
function allowDrop(ev) {ev.preventDefault();}
function drag(ev) {ev.dataTransfer.setData("text/html", ev.target.id);}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text/html");
ev.target.appendChild(document.getElementById(data));
}
</script>
<p>Drag the C# Tutorial image into the rectangle:</p>
<div id="div1" style="width:350px;height:100px;padding:10px;border:1px solid #aaaaaa;"
ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="C# Tutorial image"
draggable="true" ondragstart="drag(event)"/>
In the example provided, we have employed the ondrop and ondragover events on a div element, while utilizing the ondragstart event on an img tag.
Output:
Drag the C# Tutorial image into the rectangle:
Note: MouseEvent is not fired during drag operation.
Stages during Drag and Drop operations
1) Make an element draggable
To enable the dragging functionality for an element, you can designate the draggable attribute as "true" for that specific element. For instance:
<img draggable = "true">
2) What to drag:
Use ondragstart and setData methods.
Define the expected behavior when the element is being dragged.
3) Where to Drop:
Use ondragover event.
4) Do the Drop:
Use ondrop event.
Supporting Browsers
| Element | Chrome | IE | Firefox | Opera | Safari |
|---|---|---|---|---|---|
| drag and drop feature | Yes | Yes | Yes | Yes | Yes |