Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery sortable disable first placeholder

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.

like image 716
mabuki Avatar asked Dec 20 '22 12:12

mabuki


2 Answers

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

like image 129
Mordhak Avatar answered Dec 26 '22 20:12

Mordhak


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

like image 44
Fenistil Avatar answered Dec 26 '22 21:12

Fenistil