HTML Drag and Drop: Events, DataTransfer, File Drops
Native drag and drop has shipped in every major browser for over a decade, and it remains the most quietly misunderstood API on the platform. The event model splits between the element being dragged and the potential drop targets, drop targets refuse drops unless they explicitly opt in, and the DataTransfer object behaves completely differently during the dragstart event than it does during drop. Each of those quirks produces a bug that looks like "drag and drop does not work" until you know which rule you violated.
This lesson builds a sortable list and a file upload zone â the two real-world uses of the API â while explaining the event sequence, the DataTransfer contract, and the accessibility cost you must pay to ship the feature responsibly.
The Event Sequence, Split in Two
Dragging generates events on two separate elements. The source element sees dragstart, drag, and dragend. Every element the pointer passes over, including the source itself, sees dragenter, dragover, dragleave, and drop. The target-side events are cancellable; dragenter and dragover must call preventDefault for the browser to permit a drop on that element at all:
| Event | Fires on | Cancelable | Typical job |
|---|---|---|---|
| dragstart | Source | Yes | Set data, set effectAllowed, add visual state |
| drag | Source | Yes | Optional progress work (rarely needed) |
| dragenter | Potential target | Yes | Highlight the zone, call preventDefault |
| dragover | Potential target | Yes | Call preventDefault or the drop is rejected |
| dragleave | Potential target | Yes | Remove highlight state |
| drop | Target | Yes | Read data, perform the move, preventDefault |
| dragend | Source | Yes | Clean up source visual state |
Forgetting preventDefault on dragover is the single most common reason drops never fire â the browser assumes you rejected the drop and shows the not-allowed cursor without raising any error.
A Sortable List That Actually Sorts
The reliable pattern for reordering is to mark the container as a drop zone, track the currently dragged element, and on every dragover compute the insertion point from the pointer's vertical position relative to the sibling midpoints:
<ul id="queue" class="queue">
<li draggable="true">Write lesson outline</li>
<li draggable="true">Record audio walkthrough</li>
<li draggable="true">Edit and publish</li>
</ul>
<script>
const queue = document.getElementById('queue');
let dragging = null;
queue.addEventListener('dragstart', (event) => {
dragging = event.target.closest('li');
dragging.classList.add('dragging');
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData('text/plain', dragging.textContent);
});
queue.addEventListener('dragend', () => {
dragging?.classList.remove('dragging');
dragging = null;
});
function insertionPoint(y) {
const items = [...queue.querySelectorAll('li:not(.dragging)')];
let closest = { offset: Number.NEGATIVE_INFINITY, element: null };
for (const item of items) {
const box = item.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
closest = { offset, element: item };
}
}
return closest.element;
}
queue.addEventListener('dragover', (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
const after = insertionPoint(event.clientY);
if (after === null) {
queue.appendChild(dragging);
} else {
queue.insertBefore(dragging, after);
}
});
queue.addEventListener('drop', (event) => {
event.preventDefault();
});
</script>
Moving the node during dragover rather than waiting for drop gives the live reordering feel users expect from board and list apps. The dragging class keeps the source element semi-transparent while it is in flight, and dropEffect must agree with effectAllowed or the browser rejects the drop in some engines.
DataTransfer: Two Personalities
During dragstart, the DataTransfer object is write-only: you may setData and set effectAllowed, and reading returns nothing. During drop on the target, it becomes readable: getData returns what was written, and files may be present as well. That split exists to prevent a dragging page from probing other pages' clipboard-like state mid-drag.
The type argument to setData is a MIME-flavored label of your choosing â text/plain for the safe default, or application/x-myapp-item for structured payloads. Custom types are not readable by other applications, which is the correct behavior for app-internal drags, but text and files are what cross the boundary when a user drags content out of the browser or in from the desktop.
effectAllowed and dropEffect form a handshake. Set effectAllowed on the source to the operations you permit, and set dropEffect on the target during dragover to what this particular zone would do. If the pair is incompatible â copy against move, for example â some browsers refuse the drop silently.
File Drop Zones
Dropping files onto a page is the same event model with files attached to the transfer object. The pattern includes a counter to defeat the dragleave flicker, because dragleave fires every time the pointer crosses a child element's boundary:
<div id="dropzone" class="dropzone" tabindex="0">
Drop files here, or press Enter to browse
<input type="file" id="picker" multiple hidden>
</div>
<ul id="file-list"></ul>
<script>
const zone = document.getElementById('dropzone');
const picker = document.getElementById('picker');
const list = document.getElementById('file-list');
let dragDepth = 0;
zone.addEventListener('dragenter', (event) => {
event.preventDefault();
dragDepth += 1;
zone.classList.add('active');
});
zone.addEventListener('dragover', (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
});
zone.addEventListener('dragleave', () => {
dragDepth -= 1;
if (dragDepth === 0) zone.classList.remove('active');
});
zone.addEventListener('drop', (event) => {
event.preventDefault();
dragDepth = 0;
zone.classList.remove('active');
for (const file of event.dataTransfer.files) {
if (file.size > 10 * 1024 * 1024) {
reportError(file.name + ' exceeds the 10 MB limit');
continue;
}
const item = document.createElement('li');
item.textContent = file.name + ' (' + Math.round(file.size / 1024) + ' KB)';
list.appendChild(item);
}
});
zone.addEventListener('click', () => picker.click());
zone.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
picker.click();
}
});
picker.addEventListener('change', () => handleFiles(picker.files));
</script>
Validate size and type on drop, before any upload starts, and keep the hidden file input wired to a keyboard-accessible control so the feature is not mouse-only. The same handleFiles function can serve both paths, which is the cleanest way to make drag and drop an enhancement rather than the only door.
Custom Drag Images
The default drag ghost is a snapshot of the source element, often at the wrong scale. setDragImage takes an element, an x offset, and a y offset â relative to the viewport at dragstart â and uses that element's rendering as the ghost. Build the custom preview offscreen, call setDragImage inside dragstart, and remove it afterward. The ghost updates live with cursor movement; it does not animate or re-render during the drag in most engines, so keep it simple.
Keep the preview element small and free of expensive rendering. Because the snapshot is rasterized at dragstart, a preview containing a large image or a complex subtree can hitch the very frame where the user begins the interaction. Rendering the preview once, reusing it across drags, and sizing it to the visual weight of the item gives a crisper result than snapshotting the live list row.
Touch Devices Never Fire These Events
The classic HTML drag events do not originate from touch input on iOS or Android. Long-press on a touch screen does not produce dragstart, which means a purely native implementation works beautifully on desktop and simply does nothing for a large share of real users. The practical options are Pointer Events with a long-press activation delay â capture the pointer, translate movement into the same insertion logic, and release on pointerup â or a maintained sortable library that already handles touch, mouse, and keyboard through one abstraction. Whatever you choose, test with an actual phone before calling the feature done; desktop-only testing hides this gap completely.
The Accessibility Bill Comes Due
None of the native drag events are reachable from the keyboard, and the API exposes no roles to assistive technology. A drag-only interface locks out keyboard users, switch users, and many touch users. The remedy is a parallel path: give each draggable item a grab button that toggles a picked-up state, let Enter or Space pick up and drop, and support arrow keys to reorder while picked up. An ARIA live region announcing "Write lesson outline, position 2 of 5" closes the loop. Libraries that abstract sortable lists increasingly ship this keyboard layer; if you hand-roll the feature, treat the keyboard implementation as part of the definition of done, not as a stretch goal.
Common Mistakes
Never calling preventDefault on dragover, so drop never fires
Fix: Cancel dragenter and dragover on every valid target element.
Reading DataTransfer during dragstart and getting nothing
Fix: Write during dragstart, read during drop â the object has two modes by design.
Relying on dragleave alone to clear drop-zone highlight
Fix: Track a depth counter across dragenter and dragleave so child elements do not flicker the state.
Shipping drag and drop with no keyboard equivalent
Fix: Add a pick-up button plus arrow-key reordering, or use a library that provides it.
Uploading files without validating size and type on drop
Fix: Check constraints synchronously on drop and report rejections before any network work.
Best Practices
- Pair every drop zone with a click-to-browse file input so the feature works on touch and with keyboards.
- Use application/x-âĻ data types for app-internal drags instead of stuffing JSON into text/plain.
- Set effectAllowed on the source and matching dropEffect on the target to keep the cursor honest.
Key Takeaways
- Drag events split between the source (dragstart, dragend) and targets (dragenter, dragover, drop).
- Targets must preventDefault on dragover or the browser rejects the drop with no error message.
- DataTransfer is writable during dragstart and readable during drop; files arrive on the drop event.
- Sort by moving the node during dragover for live reordering; defeat dragleave flicker with a depth counter.
- Native drag and drop has no keyboard support â a parallel accessible path is mandatory, not optional.