Is there a way I can disable the first placeholder in a sortable unordered list?
I still want to be able to sort the first item (i.e. all items should be draggable), but I don't want any of the items after the first one to be able to be dropped above the first.
I have this sort of working but instead of having the first placeholder disabled, when an item is dropped the sort is cancelled:
$(".sortable").sortable({
beforeStop: function(event, ui) {
if(ui.placeholder.index() <= 1) {
$(this).sortable('cancel');
} else {
//sort item
}
}
});
Any pointers would be much appreciated.
I found a solution for this issue. Your code was not that far from my solution.
The idea is to use change
option to show/hide placeholder depending on its position and to cancel drop if position is the first.
The code (jsFiddle here):
var cancelRequired = false;
$("#sortable1").sortable({
placeholder: "sortable-placeholder",
change: function(event, ui) {
if (ui.placeholder.index() < 1) {
$(ui.placeholder).css('display', 'none');
} else {
$(ui.placeholder).css('display', '');
}
},
beforeStop: function(event, ui) {
cancelRequired = (ui.placeholder.index() <= 1);
},
stop: function() {
if (cancelRequired) {
$(this).sortable('cancel');
}
}
});
The hack used in beforeStop
and stop
is done because of a bug when trying to call cancel directly inside beforeStop
. More info here which send me to this link.
This code has been tested with jQuery 1.8.2 and jQuery-ui 1.9.2
Here is a more simpler way to do it, and by this way the revert function works too. For this to work, you should add a class to your first item.
HTML:
<ul id="sortable">
<li class="no_sort sortable_first">First item</li>
<li>Second Item</li>
<li>Third Item</li>
</ul>
Script:
$('#sortable').sortable({
placeholder: 'sortable_placeholder',
cancel: '.no_sort',
opacity: 0.5,
revert: 100,
change: function(event, ui) {
if (ui.placeholder.index() < 1) {
$('.sortable_first').after(ui.placeholder);
}
}
});
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With