Lesson 31 of 55 · HTML
HTML5 Drag-and-Drop API
Duration: 9 min
Native Drag‑and‑Drop
HTML5 adds drag‑and‑drop events to any element with the draggable attribute.
<ul id='source'>
<li draggable='true' id='item1'>Item 1</li>
<li draggable='true' id='item2'>Item 2</li>
</ul>
<ul id='target'></ul>
<script>
const source = document.getElementById('source');
const target = document.getElementById('target');
source.addEventListener('dragstart', e => {
e.dataTransfer.setData('text/plain', e.target.id);
});
target.addEventListener('dragover', e => e.preventDefault());
target.addEventListener('drop', e => {
e.preventDefault();
const id = e.dataTransfer.getData('text/plain');
const dragged = document.getElementById(id);
target.appendChild(dragged);
});
</script>
Accessibility
- Add
aria-grabbed(true/false) to indicate whether an element is being dragged. - Use
aria-dropeffecton the drop target to describe the permitted operation (move,copy). - Provide a keyboard alternative (e.g., arrow‑key re‑ordering) because many screen‑reader users cannot use drag‑and‑drop.
Common pitfalls
- Forgetting
e.preventDefault()ondragoverprevents dropping. - Using
text/plainas the only MIME type may limit complex data; other types (e.g.,text/uri-list) can be used.
Quick checklist for drag‑and‑drop
- Elements have
draggable='true'? ✅ dragoverevent prevents default behaviour? ✅dataTransferused correctly with a MIME type? ✅- ARIA attributes (
aria-grabbed,aria-dropeffect) added? ✅ - Keyboard fallback implemented? ✅
Tip: For sortable lists, consider a lightweight library like SortableJS that handles ARIA and keyboard shortcuts out of the box.