HTML - HTML Drag and Drop API
The HTML Drag and Drop API allows users to click on an element, drag it to another location, and drop it there. This feature is commonly used in modern web applications such as file uploads, task management boards, image rearranging systems, and interactive dashboards.
Basic Concept
Drag and Drop works using two main elements:
-
Draggable element – the item that the user moves.
-
Drop target – the area where the item is placed.
An element becomes draggable when the attribute draggable="true" is added.
Example:
<p draggable="true">Drag me</p>
Important Drag and Drop Events
HTML uses several events to control dragging behavior.
-
dragstart
Triggered when dragging begins. -
drag
Fired continuously while the element is being dragged. -
dragover
Occurs when a dragged item moves over a drop target.
This event must prevent default behavior to allow dropping. -
drop
Executes when the element is released onto the target. -
dragend
Runs after the drag operation is finished.
Simple Example
<!DOCTYPE html>
<html>
<body>
<div id="dragItem" draggable="true" ondragstart="drag(event)">
Drag this box
</div>
<div id="dropArea"
ondragover="allowDrop(event)"
ondrop="drop(event)"
style="width:200px;height:100px;border:1px solid black;">
Drop here
</div>
<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>
</body>
</html>
How It Works
When the user starts dragging, the dragstart event stores the element’s data.
The dragover event allows the drop area to accept the element.
The drop event retrieves the stored data and places the dragged element inside the drop target.
DataTransfer Object
The DataTransfer object is used to store and retrieve information during dragging.
Important methods:
setData() – saves dragged data
getData() – retrieves dragged data
clearData() – removes stored data
Practical Uses
Drag and Drop API is used in:
File upload systems
Kanban boards like task managers
Image gallery sorting
Shopping cart interfaces
Game development interfaces
Advantages
Improves user interaction
Provides visual feedback
Reduces manual input actions
Creates modern interactive interfaces
Limitations
Requires JavaScript support
Touch device support may need extra handling
Complex layouts may require additional logic
The HTML Drag and Drop API helps developers build interactive and user-friendly web applications by allowing direct manipulation of webpage elements.