Yuriy Tkachyk
Yuriy Tkachyk

Reputation: 1

Jquery sortable limited movement

I have sortable list of items (li's). I need add posability to move each item only up + 1 position index or down -1 position index.(So every drag item should be able to move only 1 step up or down). Please help to solve this problem. Thank you.

Upvotes: 0

Views: 57

Answers (2)

Yuriy Tkachyk
Yuriy Tkachyk

Reputation: 1

I found solution:

$("#sortable").sortable({
    start: function(event, ui) {
        currenPos = ui.item.index();
        console.log("Old position: " + currenPos);
    },
    stop: function(event, ui) {
        stopPos = ui.item.index();
        console.log("New position: " + stopPos);
        if((currenPos + 1) < stopPos || (currenPos - 1) > stopPos) {
          alert("You can move only for one position up or down.");
          $(this).sortable("cancel");
        }
    }
});
$("#sortable").disableSelection();

Upvotes: 0

Darek MST
Darek MST

Reputation: 117

You may to add some class to next and prev elements and check it in Stop or beforeStop event. It something like:

  $(function() {
   $( "#yourlist" ).sortable({
        start:function(e,ui){
        $(".item2").removeClass("item2");
        return true;
        },
        beforeStop:function(e,ui){

        //checking if item2 on placeholder and mark item
        },
        stop:function(e,ui){

        //checking, if not return false
        },
        sort:function(e,ui){
        $(".ui-sortable-helper").next().addClass("item2");
        $(".ui-sortable-helper").prev().addClass("item2");
        }
});
});

Upvotes: 0

Related Questions