user1956149
user1956149

Reputation: 75

jQuery Sortable by one position vertically only

I am trying to restrict a jQuery sortable list so that the user can only drag by one position at a time e.g. you can only move up or down one position in the list no skipping multiple li's. Is this possible? I have the vertical dragging implemented quite easily by having:

$( "#sortable" ).sortable({
        containment: 'parent',
        axis: 'y'
});

Any ideas? Thank you

Upvotes: 1

Views: 1423

Answers (1)

Fedor Shihantsov
Fedor Shihantsov

Reputation: 200

The idea is that in the mousedown event reinstall sortable.items:

$(function() {
$( "#sortable1" ).sortable({
  items: "li:not(.ui-state-disabled)",
  start: function (event, ui) {$( "#sortable1" ).sortable({items: ">*"})},
  stop: function (event, ui) {$( "#sortable1" ).sortable({items: ">*"})}
});

$( "#sortable2" ).sortable({
  cancel: ".ui-state-disabled"
});

$( "#sortable1 li, #sortable2 li" ).disableSelection();     
});

$('#sortable1 li').one('mousedown', function(e) {
$('#sortable1 li').removeClass("ui-state-disabled");
var downID = $(this).attr("id");
var priorItem = null;
var currentItem = null;
var nextItem = null;
var currentID = null;
var skipIteration = false;
$("#sortable1 li" ).each(function( index ) {
$(this).addClass("ui-state-disabled");
if (!skipIteration)
{
    if (!(currentItem == null))
    {
      nextItem = this;
      skipIteration = true;
    }

    if (!skipIteration)
    {
      currentID = $(this).attr("id");
      if (downID == currentID)
      {
        currentItem = this;
        //alert(currentID);
      }
      else
      {
          priorItem = this;
      }
    }
}

});  

if (priorItem !== null)
{
   $(priorItem).removeClass("ui-state-disabled");
}
if (currentItem !== null)
{
   $(currentItem).removeClass("ui-state-disabled");
}
if (nextItem !== null)
{
   $(nextItem).removeClass("ui-state-disabled");
}

$( "#sortable1" ).sortable({items: "li:not(.ui-state-disabled)"})

});

http://jsfiddle.net/qnT6x/2/

Also please see: http://jqueryui.com/sortable/#items

Upvotes: 1

Related Questions