Array out of bound
Array out of bound

Reputation: 1133

jQueryUI Sortable Change event fires multiple times on single change

link to jsFiddle : http://jsfiddle.net/k8wYF/1/ (working)

var count;
$("#sortable").sortable({
    start : function(){
               count = 0;
            },
    change : function(){
                 count++;                
            },
    stop : function(){
                 alert(count);          
            }
});
$("#sortable").disableSelection();​

on single change

count : 1

but, i want to refresh sortable on sortableStart

link to jsFiddle : http://jsfiddle.net/k8wYF/ (not working)

var count;
$("#sortable").sortable({
    start : function(){
               $("#sortable").sortable("refresh");       //refresh sortable
               count = 0;
            },
    change : function(){
                 count++;                
            },
    stop : function(){
                 alert(count);          
            }
});
$("#sortable").disableSelection();​

then, on single change

count : 16  (multiple times)

Upvotes: 1

Views: 2279

Answers (2)

J. Tanner
J. Tanner

Reputation: 575

Change appears to fire every time an element changes, so you're getting an increment with each moved li within the list. I switched it to update and took out the refresh and it seems to give the right count.

var count = 0;

$("#sortable").sortable({
    stop : function(){
                 alert(count);          
    },
    update : function(){
                 count++;  
    }
});

$("#sortable").disableSelection();

You can also put the refresh back in, just don't reset your count to 0 each time and it seems to keep track well enough. Though, without more info on what you want, I can't really help much more.

Upvotes: 2

Nope
Nope

Reputation: 22339

From the docs

Change

This event is triggered during sorting, but only when the DOM position has changed.

Refresh

Refresh the sortable items. Custom trigger the reloading of all sortable items, causing new items to be recognized.

What you are experiencing is normal. When refreshing, all items are moved into the expected positions, altering the DOM, thus triggering the changed event each time.

If you want to add code to the change event, make sure it is code you want to execute at each change.

If you want to add code to only execute when sorting is finished, add it to either stop or update.

Update

This event is triggered when the user stopped sorting and the DOM position has changed.

Stop

This event is triggered when sorting has stopped.

Depending on what your code will do, make sure you add it to the appropriate event.

Upvotes: 4

Related Questions