Sortable
Explanation #
Datastar allows you to listen for custom events using data-on-*
and react to them by modifying signals.
1<p data-signals-order-info="'Initial order'" data-text="$orderInfo"></p>
2<div id="sortContainer" data-on-reordered="$orderInfo = event.detail.orderInfo">
3 <a class="button">Item 1</a>
4 <a class="button">Item 2</a>
5 <a class="button">Item 3</a>
6 <a class="button">Item 4</a>
7 <a class="button">Item 5</a>
8</div>
9
10<script type="module">
11 import Sortable from 'https://cdn.jsdelivr.net/npm/sortablejs/+esm'
12 const sortContainer = document.getElementById('sortContainer')
13 new Sortable(sortContainer, {
14 animation: 150,
15 ghostClass: 'opacity-25',
16 onEnd: (evt) => {
17 sortContainer.dispatchEvent(new CustomEvent('reordered', {detail: {orderInfo: `Moved from ${evt.oldIndex} to ${evt.newIndex}`}}));
18 }
19 })
20</script>
We create an orderInfo
signal and modify it whenever a reordered
event is triggered.
We instruct the SortableJS library to dispatch a custom event reordered
whenever the sortable list is changed. This event contains the order information that we can use to update the orderInfo
signal.