Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the position of the element in a list when it's drag/dropped (ui.sortable)

I have a sortable list like this one: http://jqueryui.com/demos/sortable

Is it possible to get the start and end position of the element in the list, when it has been moved? I'm talking about their position number, in the list.

For example, if I move element 2 to position 5 in the list, I'd like to assign those two numbers to variables.

I'm new to jQuery - any help would be much appreciated.

like image 638
Wurlitzer Avatar asked Mar 14 '10 13:03

Wurlitzer


1 Answers

  • demo: http://so.lucafilosofi.com/getting-the-position-of-the-element-in-a-list-when-its-drag-dropped-ui-sortable/

SOLUTION:

$(function() {
    $('ul#sortable').sortable({
        start: function(event, ui) {
            var start_pos = ui.item.index();
            ui.item.data('start_pos', start_pos);
        },
        update: function(event, ui) {
            var start_pos = ui.item.data('start_pos');
            var end_pos = ui.item.index();
            alert(start_pos + ' - ' + end_pos);
        }
    });
});
  • NOTE: Updated to make use of jQuery data() method under advice of Alconja
like image 155
Luca Filosofi Avatar answered Sep 29 '22 12:09

Luca Filosofi