DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Drag and Drop List with JavaScript

Drag and drop is one of those interactions that feels like magic until you build it — then you realise the browser already does most of the work. The HTML Drag and Drop API has been around for years, and a sortable list is the perfect first project for it.

What you are building

A list of items you can pick up with the mouse and drop in a new position, with the order updating live.

The HTML: make items draggable

<ul id="task-list">
  <li draggable="true">Learn JavaScript basics</li>
  <li draggable="true">Build a small project</li>
  <li draggable="true">Deploy it online</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

One attribute, draggable="true", is all it takes to make an element pick-up-able.

The JavaScript: three events do everything

const list = document.querySelector('#task-list');
let draggedItem = null;

list.addEventListener('dragstart', (e) => {
  draggedItem = e.target;
  e.target.classList.add('dragging');
});

list.addEventListener('dragover', (e) => {
  e.preventDefault(); // Required — without this, dropping is blocked
  const after = getAfterElement(list, e.clientY);
  if (after) list.insertBefore(draggedItem, after);
  else list.appendChild(draggedItem);
});

list.addEventListener('dragend', () => {
  draggedItem.classList.remove('dragging');
});

function getAfterElement(container, y) {
  const items = [...container.querySelectorAll('li:not(.dragging)')];
  return items.find((item) => {
    const box = item.getBoundingClientRect();
    return y < box.top + box.height / 2;
  });
}
Enter fullscreen mode Exit fullscreen mode

The trick is dragover: as you move the mouse, it finds the first item whose middle is below your cursor and inserts the dragged item before it. That is the whole reordering logic.

Make it visible

li.dragging {
  opacity: 0.4;
}
Enter fullscreen mode Exit fullscreen mode

One line of CSS, and users can see what they are holding. Small feedback like this is what separates a feature that works from a feature that feels good.

The one thing to remember

Always call e.preventDefault() in dragover. Without it the browser blocks the drop entirely, and your list silently does nothing — the most common drag-and-drop bug, and the hardest to spot because there is no error message.

Top comments (0)