Sortable

Table of Contents

Basic Usage

The k-sortable component allows users to reorder items by dragging them. Wrap your items in a k-sortable container and use k-sortable-item for each item. Each item automatically gets a drag handle.

<k-sortable>
<k-sortable-item>Item 1</k-sortable-item>
<k-sortable-item>Item 2</k-sortable-item>
<k-sortable-item>Item 3</k-sortable-item>
<k-sortable-item>Item 4</k-sortable-item>
</k-sortable>

Drag items by their handle to reorder them.

Item 1 Item 2 Item 3 Item 4

Sort Event

Listen to the sort event on the k-sortable container to be notified when items are reordered.

<k-sortable id="sortableExample">
<k-sortable-item>Apple</k-sortable-item>
<k-sortable-item>Banana</k-sortable-item>
<k-sortable-item>Cherry</k-sortable-item>
<k-sortable-item>Date</k-sortable-item>
</k-sortable>
<p id="sortOutput">Reorder items to see the event fire</p>
<script>
document.getElementById('sortableExample').addEventListener('sort', () => {
const items = Array.from(document.getElementById('sortableExample').children)
.map(item => item.textContent);
document.getElementById('sortOutput').textContent = `Order: ${items.join(', ')}`;
});
</script>
Apple Banana Cherry Date

Reorder items to see the event fire

JavaScript Reference

Constructor

new Sortable()
Extends LitElement

The container component that manages sortable items.

new SortableItem()
Extends LitElement

An individual sortable item with a drag handle.

Requirements

Properties

Sortable

The Sortable container has no public properties.

SortableItem

sorting: boolean

A boolean indicating if the item is currently being dragged. This property is reflected as an attribute and automatically set by the drag handlers. When true, the item has reduced opacity.

Methods

Sortable

getCursorElement(): [Element, string] | null

Returns the element and position ('before' or 'after') where the dragged item should be inserted based on the current cursor position. Returns null if no valid target is found.

SortableItem

sortable: Sortable

A getter that returns the parent k-sortable element using closest('k-sortable').

Events

sort

Dispatched by the k-sortable container when an item is dropped in a new position. The event bubbles. Use this event to save the new order or update your application state.