Keeping track of indexes while dragging in jQuery ui.sortable

While you’re handling a drag operation in the jQuery UI Sortable handler, there’s a few small issues that might almost drive you insane. These two solutions are based on information from various places on the net (such as a few discussions on Stack Overflow).

If you want to keep track of which location the item you’re dragging originated from, you can attach to the ‘start’ event in the Sortable configuration constructor. Use this event to attach the origin index as a data element:

start: function(event, ui) {
    ui.item.data('originIndex', ui.item.index());
},

If you want to find out what index the user is currently hovering above (to change the numbering of a list instantly), you can use the same method on the placeholder element (available as ui.placeholder, so to fetch the current index the user is hovering over, call ui.placeholder.index()). There is however a gotcha’ here, as the original element is still present in the list – just allow to float freely around (the dragging action). We handle this by fetching the origin index and subtracting one if we’re after the location we started at.

You can handle these events in the ‘change’ event handler:

change: function (event, ui) {
    var originIndex = ui.item.data('originIndex');
    var currentIndex = ui.placeholder.index();

    if (currentIndex > originIndex)
    {
        currentIndex -= 1;
    }

    // do magic
}

7 thoughts on “Keeping track of indexes while dragging in jQuery ui.sortable”

  1. I’m trying this on a table where I used sortable() on the tbody and it’s failing to get the index of the row I’m dragging. Do you know any fix for this?

  2. Hi Charles, I’ve added a more extensive example of how you can do this at the post referenced in the trackback above.

    Hopefully that helps, otherwise feel free to add a comment.

  3. I was using an older version of jQuery (1.3.x), after upgrading to 1.4.2 everything worked!

    (.. sorry Charles, I deleted your comment after akismet put it in the wrong category, so I had to retype this from my memory.. –mats)

  4. Thanks for great post, after drag and drop i want to reindex rows, but do not find any to do so, will you please help me out?

Leave a Reply

Your email address will not be published. Required fields are marked *