Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if element position was changed in Jquery UI sortable

I use the following code to reorder items on my website:

$(document).ready(function () {
    $("#my-list").sortable({
        stop: function (event, ui) {
            var id = $(ui.item).attr('id');

            var url = '/en/account/changeposition?id=idreplace&position=posReplace';

            url = url.replace("idreplace", id);
            url = url.replace("posReplace", ui.item.index());

            window.location.href = url;
        },
        distance: 15
    });
});

However, even if I don't change element position and place element at the same place, Jquery UI will call 'stop'-function.

Is it possible to detect if element index (position) was changed without using custom data attributes?

// I would like to avoid adding custom data attributes like this:
<li id="id100" data-original-position="1"></li>
<li id="id101" data-original-position="2"></li>
like image 429
user1613797 Avatar asked Jun 03 '13 09:06

user1613797


Video Answer


1 Answers

Have a look at this answer.

It worked for me as follows:

$(selector).sortable({
    start: function(event, ui) {
        ui.item.data('start_pos', ui.item.index());
    },
    stop: function(event, ui) {
        var start_pos = ui.item.data('start_pos');
        if (start_pos != ui.item.index()) {
            // the item got moved
        } else {
            // the item was returned to the same position
        }
    },
    update: function(event, ui) {
        $.post('/reorder', $(selector).sortable('serialize'))
            .done(function() {
                alert('Updated')
            });
        }
});
like image 169
savedario Avatar answered Sep 23 '22 10:09

savedario