Skip to content
SortableExamples

Vanilla JS — Swap two items

comins-sortable@0.1.6Vanilla JS

Use swap in Vanilla JS to exchange only two items and inspect the completion event.

Dropping A on the center of C in [A, B, C, D] produces [C, B, A, D]. Only the two items exchange positions; B and D remain. Intervening items are not shifted as they would be for insertion.

  1. Drag the A handle to the center of C and release.
  2. Check JSON for status: "dropped", change.operation: "swap", change.itemId: "A", and change.swapItemId: "C".
  3. Start another drag and cancel with Escape; order remains unchanged.
  4. Reset returns to A, B, C, D.
Option Value/purpose
swap true — exchanges source and target within the same area.
direction "vertical" — this example uses one vertical list.
itemKey or data-sortable-id Supplies identity retained across movement.
handle ".task-handle" — restricts pointer input to handles.

createSortable · DOM

Vanilla applies the DOM swap. Swapping the elements again in a consumer onChange callback would undo it, so this example only reads the final result in onAfterDrag. Destroy the instance when its host disconnects.

This is a same-area, single-item swap. Grid collision, multiDrag, threshold/invertSwap combinations, and cross-area delivery remain separate scenarios. This pointer-based example does not claim full keyboard reordering simply because its handle is focusable.

Advanced sorting guide · Core lifecycle · Vanilla instance · Ordinary list transfer

Drop the A handle onto the center of C.
A
B
C
D

A, B, C, D

null