Skip to content
jshacks.dev
Browser

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.

1 min read
Summarize in AI

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.

sortable.jsJavaScript
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(', '));
});
Text
write, test, ship

Each 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.

Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.