Drag and drop, and keeping order
Reordering by drag has two halves: the gesture, which needs a no-drag alternative, and the saved order, which should survive a drop, a keyboard move and a second editor without rewriting the whole list.
What it is
A sortable list is two jobs. The first is the gesture: picking an item up, showing where it will land, dropping it, and offering a way to do the same thing without dragging. The second is the order itself: what you store so the list comes back in the same sequence after a reload, on another device, and after someone else has moved an item too. It's easy to spend a whole answer on the gesture and treat the order as "update the index". A strong answer designs each half on its own terms.
The browser's own API treats images, links and text selections as draggable already; for anything else you set draggable="true" on the element. dragstart fires on the item being dragged and is the moment to write to dataTransfer, the data store that travels with the drag and holds text items, which must be strings, and file items; the browser also builds a translucent copy of the element to follow the pointer, which setDragImage() can replace. As the pointer moves, dragenter and dragleave fire on elements it passes and dragover fires repeatedly on the one it's inside. Most elements refuse drops by default: calling preventDefault() on dragover is what turns an element into a drop target, and drop is where you read the data back with getData(). dragend then fires on the source whether or not the drop succeeded, which makes it the place to remove placeholders and highlight classes. While a drag is in progress the browser suppresses other input events, so a keyboard shortcut to cancel won't reach your code.
Pointer events are the other route: a single event model covering mouse, pen and touch, with pointerType saying which one fired. You begin on pointerdown, move the item yourself on pointermove, and commit on pointerup. Two details make this work on a phone. setPointerCapture() retargets later pointer events to the element you name, so the item keeps receiving moves after the finger slides off it, and the capture is released on its own at pointerup or pointercancel. touch-action: none on the handle tells the browser not to apply its default panning or zooming to that region; without it the browser may decide the gesture is a scroll and fire pointercancel, which ends your drag. You draw the placeholder and work out the drop index yourself, which is more code but gives you the animation and auto-scroll behavior you want.
For the saved order, the plainest scheme is an integer position per row. A move then renumbers the rows between the old and new slots, and when two people move items in overlapping ranges at the same time, without a transaction or a version check, the later batch of writes can undo part of the earlier one. Fractional indexing avoids that: each item carries a key, and the list order is the sort order of the keys. To place an item between two neighbors you pick a key between theirs, and a move writes one row. Figma uses this for the ordered children in its documents: each key is a fraction strictly between 0 and 1, stored as a string over a base-95 alphabet so that a new key can be made before, after or between existing ones without losing precision. The same write-up is candid about the costs: keys grow longer over many edits, inserts from different clients may interleave, and two clients choosing a key between the same two neighbors produce an identical key, which the server resolves by giving the second insert a fresh one.
// Reorder on screen first, then persist a single row.
async function moveItem(items: Item[], id: string, toIndex: number) {
const from = items.findIndex((it) => it.id === id);
const next = [...items];
const [moved] = next.splice(from, 1);
next.splice(toIndex, 0, moved);
const before = next[toIndex - 1]?.key ?? null; // null: nothing before it
const after = next[toIndex + 1]?.key ?? null; // null: nothing after it
const key = keyBetween(before, after); // a string that sorts between them
next[toIndex] = { ...moved, key };
render(next); // optimistic
try {
const res = await fetch(`/items/${id}`, {
method: 'PATCH',
body: JSON.stringify({ key }),
});
if (!res.ok) throw new Error('reorder failed');
} catch {
render(items); // put the old order back
showError('Could not save the new order');
}
}When to use it
Reach for the native drag events when the data crosses a boundary: a file dragged in from the operating system, or an item dragged out to another document or application. The data store holds serialized strings for exactly that reason, and the browser supplies the cursor feedback for copy, move and link through dropEffect and the ghost image with little code from you. A mouse-driven list on a desktop admin page is also well served by it.
Reach for pointer events when the list has to work under a finger, when you want the item to animate as it moves, or when a long press should start the drag. One handler set covers mouse, pen and touch, pointer capture keeps the moves flowing to your element, and touch-action lets you decide which gestures the browser keeps for scrolling.
Whichever route you take, add a path that doesn't drag. WCAG 2.2 Success Criterion 2.5.7, Dragging Movements (Level AA), asks that anything operated by a dragging movement can also be done with a single pointer and no drag, unless dragging is essential to the function. The W3C's own examples include a sortable list that shows move up and move down controls once an item is tapped, and a task board with a pop-up menu for moving a card to another column. The criterion is kept separate from keyboard access because a touchscreen user may have no physical keyboard; in practice the same buttons give keyboard users their path as well. Our advice: build the buttons first and put the drag on top, and make the new position readable to screen reader users (see Accessible widgets).
Reach for fractional keys when the list is long, when several people can edit it at once, or when a move has to be a single-row write so it can be sent, retried and merged as one small message. Reordering touches a single value, which is also what makes an undo cheap: restore the previous key.
When not to
A short list with one owner, such as five sections on a settings page or a personal checklist, doesn't need fractional keys. Store the whole ordered array of ids in one field, or keep integer positions and renumber them in one request. Both are easier to read in a query and to debug, and the costs that come with fractional keys, longer keys over time and a tie-break for identical keys, buy you nothing at that size.
Don't use fractional indexing where interleaving would corrupt meaning. Two users inserting runs of items at the same spot can end up interleaved, which is tolerable for layers in a design file and wrong for characters in a text. Operational transformation linearizes concurrent inserts instead, at a much higher implementation cost; see Operational transforms and CRDTs.
Sometimes dragging isn't worth building at all. For three options, or for a list where the common move is "send to top", the buttons or a "move to" menu are the whole feature, and they already satisfy the no-drag requirement. Likewise, skip the native API when the dragged item's look has to match your design closely or animate while moving: the browser draws the drag image itself, with setDragImage() as the swap-in, and the rest of the input is suppressed while the drag runs.
Compared
| Option | How it works | Right choice when | What it costs |
|---|---|---|---|
Native drag events |
| Data crosses a window or comes from the OS; desktop mouse lists | Browser-drawn ghost image; other input suppressed during the drag |
Pointer events |
| Touch, custom visuals, auto-scroll | You write hit testing, placeholder and scrolling yourself |
Buttons or a move menu | Select an item, then tap up, down or "move to" | Required for a drag you built, unless dragging is essential to the function; the whole feature for short lists | More controls on screen |
Ordered array of ids | One field holds the full order | One owner, short list | Whole list rewritten per move; two editors' saves can overwrite each other without a version check |
Integer position | Rows hold 1, 2, 3; a move renumbers the rows in between | Small lists, plain | Many rows per move; overlapping moves from two editors can leave gaps or duplicates unless serialized |
Fractional key | A sortable key between the neighbors' keys; a move writes one row | Long lists, several editors, realtime sync | Keys grow; identical keys need a tie-break, such as on the server; concurrent inserts may interleave |
In a picture
Step 1 of 3
The drop lands
Someone drops card B between C and D, or presses "move down" until it sits there. The list reorders on screen at once, before anything is sent.