Projects
Drag & Drop
Build a Kanban board with drag and drop. Master the HTML5 Drag and Drop API, dataTransfer, visual feedback, sortable lists, and touch support with Pointer Events.
What You Will Build
1
HTML5 DnD API
dragstart, dragover, drop, dragend event lifecycle
2
Visual Feedback
Opacity, highlight drop targets, drag-over styles
3
Sortable List
Reorder items within the same container
4
Touch Support
touchstart/touchmove/touchend for mobile devices
DnD Event Flow
| Event | Fires On | When | Key Action |
|---|---|---|---|
| dragstart | Draggable | Drag begins | Set dataTransfer data, add .dragging class |
| drag | Draggable | Continuously while dragging | Update position (throttle!) |
| dragenter | Drop target | Enters target | Add .drag-over visual feedback |
| dragover | Drop target | Hovering over | MUST call preventDefault() to allow drop |
| dragleave | Drop target | Leaves target | Remove .drag-over feedback |
| drop | Drop target | Released on target | Move item, call preventDefault() |
| dragend | Draggable | Drag ends (any outcome) | Remove .dragging class, clean up |
Common Pitfalls
Forgetting preventDefault() in dragover — without it, the browser rejects the drop and fires no drop event
Always call e.preventDefault() inside dragover AND set e.dataTransfer.dropEffect = 'move'.
Applying drag styles synchronously in dragstart — browser captures element snapshot before style applies
Use requestAnimationFrame(() => el.classList.add('dragging')) to defer the style until after snapshot.
dragleave fires when moving over child elements — drop target visually flickers
Check if (!element.contains(e.relatedTarget)) before removing drag-over class to ignore child transitions.
No touch support — HTML5 DnD API doesn't fire on mobile touchscreen
Implement touchstart/touchmove/touchend handlers separately, or use a library like SortableJS.
Build It Live
Code Editor
<ul id="list">
<li draggable="true">1. HTML</li>
<li draggable="true">2. CSS</li>
<li draggable="true">3. JavaScript</li>
<li draggable="true">4. React</li>
</ul>
<p>Drag items to reorder them.</p>Preview
Drag and Drop — step by step
1
dragstart and dataTransfer
When the user grabs an element, the dragstart event fires. Use event.dataTransfer.setData to attach a payload (like an element ID). This data travels with the drag gesture to wherever the user drops it.
1 of 4
💡dragover Must Call preventDefault
This is the single most common drag-and-drop bug. If you forget event.preventDefault inside the dragover handler, the browser treats the element as a non-droppable area and the drop event will silently not fire — no error, just nothing happens.
🎯 Quick Check
Why must you call event.preventDefault() inside the dragover event handler?
Next project