Drag and Drop Sortable Demo

This demo demonstrates how to integrate htmx with the Sortable.js library to create a reorderable list. When an item is dropped into a new position, htmx automatically sends the new order to the server using a POST request.

Sortable List

Drag the handles to reorder items.

Updating...
Item 1 Order: 1
Item 2 Order: 2
Item 3 Order: 3
Item 4 Order: 4
Item 5 Order: 5
How it works
  • Sortable.js: Handles the drag-and-drop UI and DOM manipulation.
  • Hyperscript: Initializes Sortable on the list element when it loads. It also listens for Sortable's onEnd callback and dispatches a standard DOM end event.
  • htmx: Listens for the end event on the form. When triggered, it collects all itemIds inputs (thanks to Sortable moving the DOM elements) and posts them to the server. It also includes the ASP.NET Core Anti-Forgery Token in the request headers via a global configuration.
  • ASP.NET Core: The OnPostReorder handler receives the array of IDs and updates the sequence in the backend.