Lesson 31 of 55
HTMLHTML5 Drag-and-Drop API
9 min
Course progress56%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 31 of 55
HTML9 min
Keep these ideas in mind as you work through the lesson.
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>
aria-grabbed (true / false) to indicate whether an element is being dragged.aria-dropeffect on the drop target to describe the permitted operation (move, copy).e.preventDefault() on dragover prevents dropping.text/plain as the only MIME type may limit complex data; other types (e.g., text/uri-list) can be used.draggable='true'? ✅dragover event prevents default behaviour? ✅dataTransfer used correctly with a MIME type? ✅aria-grabbed, aria-dropeffect) added? ✅Tip: For sortable lists, consider a lightweight library like SortableJS that handles ARIA and keyboard shortcuts out of the box.