JQuery sortable disable first placeholder

Is there a way to disable the first placeholder in a sorted unordered list?

I still want to be able to sort the first element (i.e. all elements must be draggable), but I do not want any elements after the first to be deleted above the first.

I have this kind of work, but instead of disconnecting the first placeholder when the item fell, the sorting is canceled:

$(".sortable").sortable({ beforeStop: function(event, ui) { if(ui.placeholder.index() <= 1) { $(this).sortable('cancel'); } else { //sort item } } }); 

Any pointers would be much appreciated.

+4
source share
2 answers

I found a solution for this problem. Your code was not so far from my decision.

The idea is to use the change option to show / hide the placeholder depending on its position and to cancel the fall if the position is the first.

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 due to an error when trying to cause cancellation directly inside beforeStop . More info here that send me to this link .

This code has been tested with jQuery 1.8.2 and jQuery-ui 1.9.2

+6
source

Here is an easier way to do this, and the return function works this way. For this to work, you must add the class to your first element.

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

+1
source

All Articles