HTML Drag and Drop API
The HTML5 Drag and Drop API allows us to drag elements (like images, text, boxes) from one place and drop them somewhere else inside the browser.

Basic Flow
- Set the element as draggable by adding draggable="true".
- Set up a handler for the drag start with ondragstart.
- Set the drop target with ondragover and ondrop.
- Prevent the default action with ondragover.
Example
<div id="dragBox" draggable="true" ondragstart="dragStart(event)" style="width:100px;height:100px;background:red;color:#fff;text-align:center;padding-top:35px;cursor:move;"> Drag Me </div> <div id="dropZone" ondrop="drop(event)" ondragover="allowDrop(event)" style="margin-top:20px;width:300px;height:150px;border:2px dashed #333;text-align:center;padding-top:60px;"> Drop Here </div>
JavaScript
<script>
function allowDrop(event) {
event.preventDefault(); // Required to allow dropping
}
function dragStart(event) {
event.dataTransfer.setData("text", event.target.id);
}
function drop(event) {
event.preventDefault();
const data = event.dataTransfer.getData("text");
const draggedElement = document.getElementById(data);
event.target.appendChild(draggedElement);
}
</script>
Key Events in the Drag and Drop API
| Event | Triggered When |
|---|---|
| dragstart | Element starts being dragged |
| drag | Element is being dragged (continuous) |
| dragend | Drag action ends |
| dragenter | Draggable enters drop zone |
| dragover | Draggable is moved over drop zone |
| dragleave | Draggable leaves drop zone |
| drop | Draggable is released over drop zone |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com