HTML Drag and Drop
Drag-and-drop UIs let people move items with a pointer. HTML marks what can be dragged; JavaScript decides what a drop means.
Direct answer
Set draggable="true" on an element, listen for dragstart, and on a target listen for dragover (call preventDefault()) and drop. Without script, dragging alone does little useful.
Minimal drag and drop
html<div id="item" draggable="true" style="padding:8px;background:#cdf;width:120px;">Drag me</div>
<div id="zone" style="margin-top:12px;padding:24px;border:2px dashed #666;">Drop here</div>
<script>
const item = document.getElementById("item");
const zone = document.getElementById("zone");
item.addEventListener("dragstart", (e) => e.dataTransfer.setData("text/plain", "item"));
zone.addEventListener("dragover", (e) => e.preventDefault());
zone.addEventListener("drop", (e) => {
e.preventDefault();
zone.appendChild(item);
});
</script>
Try it
- Paste the example and open it
- Drag the box into the dashed zone
- Change the zone styling
- Remember keyboard users need alternative UI for the same action
Easy mistakes
- Forgetting
preventDefaultondragoverso drop never fires - Building DnD-only interfaces with no keyboard alternative
- Overusing DnD when a simple button would do
Summary
draggableenables dragging- JS handles drop behavior
- preventDefault on dragover matters
- Offer non-drag alternatives for accessibility
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top