Sortable#
Demo#
Order Info: Order Info
Open your console to see an event results
Item 1
Item 2
Item 3
Item 4
Item 5
Explanation#
In the original example you had to hook into HTMX’s events. With Datastar, you can easily listen for custom events using data-on-*
, and update signals to effect change.
<div data-signals="{orderInfo:''}">
<div>OrderInfo: <span data-text="orderInfo.value">Order Info</span></div>
<div id="sortContainer"
data-on-reordered="orderInfo.value = event.detail.orderInfo; console.log(`You could send this to the server! ${orderInfo.value}`)"
>
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
</div>
<script type="module" src="/static/js/sortable.js"></script>
</div>
The HTML looks pretty straightforward. Create an orderInfo
signal and modify it (and send to the server) whenever a reordered
event is triggered.
import Sortable from 'https://cdn.jsdelivr.net/npm/sortablejs@1.15.3/+esm'
const sortContainer = document.getElementById('sortContainer')
new Sortable(sortContainer, {
animation: 150,
ghostClass: 'opacity-25',
onEnd: (evt) => {
sortContainer.dispatchEvent(new CustomEvent('reordered', {detail: {orderInfo: `Moved from ${evt.oldIndex} to ${evt.newIndex}`}}));
}
})
Here we are dispatching 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.
Anything you can do in HTMX or Alpine should be possible in Datastar.