Emmanuel Akinfulubi

JavaScriptEvents

Drag and drop to reorder a list in JavaScript

Advanced · 4 min read

To-do apps, playlists and project boards let you grab an item and drop it somewhere else in the list. Browsers have drag and drop built in, so you don't have to track the mouse yourself. You do have to know one rule, though, because without it the drop simply never happens, and nothing tells you why.

In this tutorial you will make a list of bus stops that can be reordered by dragging, and a keyboard-friendly way to do the same thing. You should know what an array is, what indexOf returns, and how addEventListener works.

The pieces of a drag

Dragging an item fires a few events, in this order:

  • dragstart fires on the item you pick up.
  • dragover fires again and again on whatever element is under the pointer while you drag.
  • drop fires on the element under the pointer when you let go.

An element can only be picked up if it has the attribute draggable="true". It is an HTML attribute, not something CSS can switch on. Here is the list:

index.html

<ul id="list">
  <li draggable="true">Ojota</li>
  <li draggable="true">Berger</li>
  <li draggable="true">Ibadan</li>
  <li draggable="true">Ilorin</li>
</ul>

The rule everyone trips on

By default, elements refuse drops. To tell the browser "you may drop here", the dragover handler must call event.preventDefault(), which cancels that default refusal. Leave it out and drop is never delivered. There is no error and no warning. This one line is the answer to "why does my drop handler never run?"

Here is the exercise. Try it yourself first, or read on and we will build it step by step.

6 Reorder a list by dragging

hard

Let items in a list be dragged into a new order. There is one non-obvious requirement without which nothing works at all.

Stuck? Three hints, smallest first
  1. 1. An element needs draggable="true" before it can be dragged.
  2. 2. dragover must call preventDefault(), or the drop event never fires.
  3. 3. Dragging is mouse-only, so provide buttons or keys that move an item as well.

Step 1: remember what is being dragged

Step 1

const list = document.getElementById('list');
let dragged = null;
list.addEventListener('dragstart', (event) => { dragged = event.target; });
list.children[0].dispatchEvent(new Event('dragstart', { bubbles: true }));
console.log(dragged.textContent); // Ojota

The listener sits on the list, not on each item. Drag events bubble up from the item to the list, and event.target is the item that was picked up. We keep it in dragged so the drop handler knows what to move.

Step 2: allow drops

Step 2

list.addEventListener('dragover', (event) => {
  event.preventDefault();
});

That's the whole step, and it is the line that makes the list a valid drop target.

Step 3: move the item on drop

When the item is dropped on another item, we move it next to that item. list.insertBefore(node, ref) puts node just before ref. If node is already in the list, it is moved, not copied.

Step 3

list.addEventListener('drop', (event) => {
  event.preventDefault();
  const target = event.target;
  if (!target || target === dragged || target.parentNode !== list) return;
  const items = [...list.children];
  if (items.indexOf(dragged) < items.indexOf(target)) {
    list.insertBefore(dragged, target.nextSibling ?? null);
  } else {
    list.insertBefore(dragged, target);
  }
});
const order = () => [...list.children].map((li) => li.textContent).join(', ');
const drag = (from, to) => {
  list.children[from].dispatchEvent(new Event('dragstart', { bubbles: true }));
  list.children[to].dispatchEvent(new Event('dragover', { bubbles: true, cancelable: true }));
  list.children[to].dispatchEvent(new Event('drop', { bubbles: true, cancelable: true }));
};
drag(0, 2);
console.log(order()); // Berger, Ibadan, Ojota, Ilorin
drag(3, 0);
console.log(order()); // Ilorin, Berger, Ibadan, Ojota

There's a lot here, so take it a piece at a time:

  • preventDefault() in drop stops the browser doing its own thing with the dropped data, such as opening it as a link.
  • The guard line ignores a drop on nothing, a drop of an item onto itself, and a drop on something that isn't one of our items.
  • list.children is not a real array, so [...list.children] copies it into one, which gives us indexOf.

The if decides which side of the target to land on. Dragging Ojota down onto Ibadan should put it after Ibadan. So when the dragged item starts above the target, we insert before the target's next sibling, which is the same as "after the target". If the target is the last item, nextSibling is null, and insertBefore(node, null) adds it at the end. Dragging upward, we insert before the target.

The drag helper fakes the three events, so we can check the order without a mouse.

Step 4: a way that doesn't need a mouse

Dragging only works with a mouse or touch. Someone using a keyboard or a switch device has no way to drag, so a list that can only be reordered by dragging can't be reordered by them at all. A move function gives them the same result with buttons or keys:

Step 4

const list = document.getElementById('list');
const order = () => [...list.children].map((li) => li.textContent).join(', ');
function move(item, direction) {
  const items = [...list.children];
  const i = items.indexOf(item);
  const j = i + direction;
  if (i === -1 || j < 0 || j >= items.length) return false;
  if (direction < 0) list.insertBefore(item, items[j]);
  else list.insertBefore(items[j], item);
  return true;
}
move(list.children[2], -1);
console.log(order()); // Ojota, Ibadan, Berger, Ilorin
console.log(move(list.children[0], -1)); // false: the first item can't go up

direction is -1 for up and 1 for down. Moving up, the item goes before its upper neighbor. Moving down, the lower neighbor goes before the item, which swaps them. The guard refuses moves off either end and returns false so the caller knows nothing happened.

The full solution

The panel builds the list, fakes a drag down and a drag up, then tests the keyboard route. Its checks confirm every item is draggable, dragging down lands after the target and dragging up lands before it, dragover really cancelled its default, no item is lost or duplicated, and moving the first item up or the last item down is refused. Press Run, then try dragging in the live demo, or focus an item and use the buttons.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const stops = ['Ojota', 'Berger', 'Ibadan', 'Ilorin'];
const list = el('ul', { id: 'list' }, stops.map((s) => el('li', { draggable: 'true' }, s)));
document.body.appendChild(list);

let dragged = null;
let dropCount = 0;
let dragoverDefaultPrevented = false;

list.addEventListener('dragstart', (event) => { dragged = event.target; });

// THE line. A drop target is only a drop target if dragover cancels the default.
// Leave this out and drop is never delivered, with no error to tell you why.
list.addEventListener('dragover', (event) => {
  event.preventDefault();
  dragoverDefaultPrevented = event.defaultPrevented;
});

list.addEventListener('drop', (event) => {
  event.preventDefault();
  dropCount++;
  const target = event.target;
  if (!target || target === dragged || target.parentNode !== list) return;

  const items = [...list.children];
  // Moving down: insert after. Moving up: insert before.
  if (items.indexOf(dragged) < items.indexOf(target)) {
    list.insertBefore(dragged, target.nextSibling ?? null);
  } else {
    list.insertBefore(dragged, target);
  }
});

// Dragging is mouse-only. This is the keyboard route to the same result.
function move(item, direction) {
  const items = [...list.children];
  const i = items.indexOf(item);
  const j = i + direction;
  if (i === -1 || j < 0 || j >= items.length) return false;
  if (direction < 0) list.insertBefore(item, items[j]);
  else list.insertBefore(items[j], item);
  return true;
}

const order = () => [...list.children].map((li) => li.textContent);
const drag = (from, to) => {
  fire(list.children[from], 'dragstart');
  fire(list.children[to], 'dragover');
  fire(list.children[to], 'drop');
};

const reset = () => {
  list.textContent = '';
  for (const s of stops) list.appendChild(el('li', { draggable: 'true' }, s));
};

console.log('start :', order());
drag(0, 2);
const afterDown = order();
console.log('dragged item 0 down onto item 2:', afterDown);

reset();
drag(3, 0);
const afterUp = order();
console.log('dragged the last up onto the first:', afterUp);
console.log('dragover cancelled its default?', dragoverDefaultPrevented, '<- required, or drop never fires');

reset();

Output


      
16 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 16 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

16 checks

test('the list starts in order', order(), stops);
test('every item is draggable', [...list.children].every((li) => li.getAttribute('draggable') === 'true'), true);
test('dragging an item DOWN puts it after the target', afterDown, ['Berger', 'Ibadan', 'Ojota', 'Ilorin']);
test('dragging an item UP puts it before the target', afterUp, ['Ilorin', 'Ojota', 'Berger', 'Ibadan']);
test('dragover cancelled its default, which is what allows drop', dragoverDefaultPrevented, true);
test('the drop handler ran', dropCount > 0, true);
test('no item was lost', afterDown.length, stops.length);
test('and none was duplicated', new Set(afterDown).size, stops.length);
test('dropping an item on itself changes nothing', (() => { const before = order(); drag(1, 1); return order(); })(), stops);
test('the keyboard route moves an item up', (() => { reset(); move(list.children[2], -1); return order(); })(), ['Ojota', 'Ibadan', 'Berger', 'Ilorin']);
test('and down again, restoring the order', (() => { move(list.children[1], 1); return order(); })(), stops);
test('moving the first item up is refused', move(list.children[0], -1), false);
test('moving the last item down is refused', move(list.children[3], 1), false);
test('and neither refusal changed the order', order(), stops);
test('the list still holds every original name', order().slice().sort(), stops.slice().sort());
test('children is a live collection, not an array', Array.isArray(list.children), false);

event.preventDefault() inside dragover is the answer to "why does my drop handler never run". By default an element refuses drops; cancelling the dragover default is what marks it as a valid drop target. There is no error and no warning — the drop event simply is not delivered. The assertion checks the cancellation actually happened.

draggable="true" is the other prerequisite, and it is an attribute rather than something you can set in CSS.

The keyboard path is not an optional extra. Drag and drop is mouse-only: there is no keyboard equivalent of a drag, so a list that can only be reordered by dragging cannot be reordered at all by someone using a keyboard, a switch or a screen reader. The move() function is the same reordering reachable another way, and it is asserted to the same standard, including refusing to move the first item up.

Common mistakes

  • Not calling preventDefault() in dragover. The drop event is never delivered, silently. This is the bug behind most broken drag and drop code.
  • Forgetting draggable="true". Without it, a list item can't be picked up at all.
  • Offering dragging as the only way. Keyboard and switch users can't drag. Give them move up and move down controls too.

Try it yourself

  1. Add a dragging class to the item on dragstart and remove it on dragend, with CSS that sets opacity: .4 on it.
  2. Give each item tabIndex = 0 so it can be focused, and add "Move up" and "Move down" buttons that call move on document.activeElement.
  3. Show the current order in a pre element under the list after every change.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.