javascripthtmlsortingsortablejs

Using sortable.js with HTML custom data attribute


How does one use HTML's custom data attribute to sort items using sortable.js?

Or how does one define custom sorting parameter using sortable.js?

For example in the code below, I'd like to sort with data-timestamp

<ul id="items">
    <li data-timestamp='1'>item Y</li>
    <li data-timestamp='2'>item B</li>
    <li data-timestamp='3'>item Z</li>
</ul>

Solution

  • Using the store feature documented here: https://github.com/SortableJS/Sortable#store

    You can pass Sortable a sorted array of the attributes, and set the dataIdAttr to 'data-timestamp'

    Sortable.create(el, {
        dataIdAttr: 'data-timestamp',
        store: {
            get: function () {
                return ['1', '2', '3'];
            }
        }
    })