jQuery UI Sortable, how to determine current location and new location in update event?

Amir picture Amir · Oct 21, 2009 · Viewed 39.8k times · Source

I have:

<ul id="sortableList">
     <li>item 1</li>
     <li>item 2</li>
     <li>item 3</li>
</ul>

I have wired into the update: function(event, ui) { } but am not sure how to get the original and new position of the element. If i move item 3 to be above item 1, I want the original position to be 2 (0 based index) and the new position of item 3 to be 0.

Answer

Rush Frisby picture Rush Frisby · Dec 9, 2011
$('#sortable').sortable({
    start: function(e, ui) {
        // creates a temporary attribute on the element with the old index
        $(this).attr('data-previndex', ui.item.index());
    },
    update: function(e, ui) {
        // gets the new and old index then removes the temporary attribute
        var newIndex = ui.item.index();
        var oldIndex = $(this).attr('data-previndex');
        $(this).removeAttr('data-previndex');
    }
});