PHP, Python and Java developer located at Hvaler, Norway. Main interests include digital mapping, search and scalability. Mats is a DZone MVB and is not an employee of DZone and has posted 28 posts at DZone. You can read more from them at their website. View Full User Profile

Keeping track of indexes while dragging in jQuery ui.sortable

06.13.2011
| 5614 views |
  • submit to reddit

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
}
From http://e-mats.org/2011/06/keeping-track-of-indexes-while-dragging-in-jquery-ui-sortable/
Published at DZone with permission of Mats Lindh, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)