Implement drag and drop sorting of a list
Reorder a list with the HTML drag and drop API using dragstart, dragover and drop, and insert the dragged item before or after the drop target.
The built-in drag and drop events are enough to reorder a short list. Mark items as draggable, remember which one is moving, and insert it where it lands.
const list = document.querySelector('#tasks');
let dragged = null;
list.addEventListener('dragstart', (event) => {
dragged = event.target.closest('li');
event.dataTransfer.effectAllowed = 'move';
});
list.addEventListener('dragover', (event) => {
event.preventDefault();
});
list.addEventListener('drop', (event) => {
event.preventDefault();
const target = event.target.closest('li');
if (!dragged || !target || target === dragged) return;
const after = event.clientY > target.getBoundingClientRect().top + target.offsetHeight / 2;
target.insertAdjacentElement(after ? 'afterend' : 'beforebegin', dragged);
console.log([...list.children].map((li) => li.textContent).join(', '));
});write, test, shipEach li has draggable="true". Calling preventDefault in dragover is what marks the list as a valid drop zone, and the drop handler moves the element to the half of the target nearest the pointer. The output is the order after dragging "ship" below "test". See the HTML Drag and Drop API.
Touch screens do not fire these events in all browsers, and nothing here works from the keyboard. Add "move up" and "move down" buttons if the order matters.