Jquery sortable 'change' event element position

dzolnjan picture dzolnjan · Feb 10, 2011 · Viewed 118.7k times · Source

Is there way to get current position of helper being dragged on over new position ?

$("#sortable").sortable({
        start: function (event, ui) {
            var currPos1 = ui.item.index();
        },
        change:  function (event, ui) {
            var currPos2 = ui.item.index();
        }
});

It seems that currPos1 and currPos2 have same value when actual change happens !

What I need to achieve is highlight to user all positions between 'start drag element' to 'currently replaced element'. Once user releases mouse button update happens and only then I get new position, but I need it before mouse release.

Answer

Luca Filosofi picture Luca Filosofi · Feb 10, 2011

UPDATED: 26/08/2016 to use the latest jquery and jquery ui version plus bootstrap to style it.

$(function() {
    $('#sortable').sortable({
        start: function(event, ui) {
            var start_pos = ui.item.index();
            ui.item.data('start_pos', start_pos);
        },
        change: function(event, ui) {
            var start_pos = ui.item.data('start_pos');
            var index = ui.placeholder.index();
            if (start_pos < index) {
                $('#sortable li:nth-child(' + index + ')').addClass('highlights');
            } else {
                $('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
            }
        },
        update: function(event, ui) {
            $('#sortable li').removeClass('highlights');
        }
    });
});