I have a list which is sortable. Before I start sorting, I want to check if all the elements of that list are valid. If not, cancel the event and leave the list intact.
The only way I have found to cancel a sort without hitting some jQuery UI bugs, is to asynchronously cancel the sort.
Using the stop option as others have suggested, is not acceptable, as it allows the user to drag the item around on the screen first, and then cancels it when they are done. This does not satisfy the OP's original concern to "prevent" dragging of certain items.
You will experience errors in jQuery UI if you try to cancel the sortable during the sort event. Errors like Uncaught TypeError: Cannot read property '0' of null
Only solution I could get to work, does have a brief flash on the screen as the user begins to drag. But it immediately cancels the drag, and doesn't have any JS errors.
var isCancel = false;
element.sortable({
start: function() { isCancel = false; },
sort: function(event, ui) { // prevent dragging if row has dynamically assigned class
if (ui.item.hasClass('no-drag')) {
isCancel = true;
// allow current jQuery UI code to finish runing, then cancel
setTimeout(function() {
element.sortable('cancel');
}, 0);
}
},
stop: function() {
if (isCancel) return;
// your normal processing here
},
});
You can use the cancel method
$("#list").sortable({
connectWith: ".connectedSortable",
items: '.sortable-item',
handle: '.handle',
placeholder: "ui-state-highlight",
stop: function (event, ui) {
console.log('stop')
if (!valid()) {
$( this ).sortable( "cancel" );
}
}
});
Demo: Fiddle