Loading...

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
HTML Code
<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

  1. Paste the example and open it
  2. Drag the box into the dashed zone
  3. Change the zone styling
  4. Remember keyboard users need alternative UI for the same action

Easy mistakes

  • Forgetting preventDefault on dragover so drop never fires
  • Building DnD-only interfaces with no keyboard alternative
  • Overusing DnD when a simple button would do

Summary

  • draggable enables dragging
  • JS handles drop behavior
  • preventDefault on dragover matters
  • Offer non-drag alternatives for accessibility

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
3
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 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