Practical Drag-to-Reorder List
Build a reorderable list with the Drag and Drop API.
Pattern Overview
To build a drag-to-reorder list, make every item draggable, store the dragged item's id in dataTransfer on dragstart, and on drop insert the dragged element before or after the target. The DOM and model stay in sync if you rebuild the order from the DOM after each drop.
Markup
Render a flat list where every li carries draggable="true" and a data-id. Keeping ids on the elements means the drag handlers do not need to query a separate state store to identify items — the element itself is the source of truth.
<ul id="list">
<li draggable="true" data-id="1">Item 1</li>
<li draggable="true" data-id="2">Item 2</li>
<li draggable="true" data-id="3">Item 3</li>
</ul>All lessons in this course
- draggable Attribute and dragstart Event
- dragover and drop Events
- dataTransfer Object
- Practical Drag-to-Reorder List