Hod do you determine the new index of an element sorted using jQuery UI sortable?
i have an un-ordered list and every list item has an id…when i drag it up or down and place it, i need to know the new position (vaguely speaking, like the id of element that moved to make room for this new element) …is that even possible?
i tried using the .mousedown and .mouseup events and getting this.id…but it returns the same element being dragged both the times.
In short we knw the element being dragged but hw can we know where it was finally laid to rest?
the code is simple…it is actually a table
---------HTML----------------
<table id="activities">
<thead>
<tr><th>Activity Name</th><th>Activity Number</th></tr>
</thead>
<tbody>
<tr id="node-1">
<td>Welcome</td>
<td>1</td>
</tr>
<tr id="node-2">
<td>Eat</td>
<td>2</td>
</tr>
<tr id="node-3">
<td>Walk</td>
<td>3</td>
</tr>
<tr id="node-4">
<td>Sleep</td>
<td>4</td>
</tr>
</tbody>
</table>
Now im making the rows sortable by jquery:
$("#activities tbody").sortable();
Now when the user drags a row up or down, i need to change the activity number accordingly…for example if he drags the “welcome” row down under the “eat” row, that will mean the the activity number of “welcome” row is now 2 (which was previously 1) and the activity number of “eat” row is 1….to display the new updated table with correct activity number, i need to know the where it was dropped.
You can use the
beforeStopfunction within thesortable()method:JS Fiddle demo;
Edited to provide information on retrieving the
idof the dropped element:JS Fiddle demo.
Edited in response to question, in comments, from the OP:
Of course:
newIndex = $(ui.helper).index('table tbody tr');This selects the current ‘helper element’, and uses the jQuery
index()method to find where that element fits within the elements returned by the selector passed to the method, in this case the elements returned bytable tbody tr. If there is more than onetableandtbodyon the page this index will be wrong, so selecting by the table’sidwould be (index('#idOfTable tbody tr')) would be preferable.theID = ui.helper.id;This returns the
idof the item held in theui.helpervariable (the just-dropped element).alert()is just a routine JavaScript alert.References:
sortable()beforeStop(from the above link, select the ‘events’ menu, and then click onbeforeStop):index().