CaffGeek
CaffGeek

Reputation: 22054

jQuery.sortable() and limiting movement

I have a rather complex UI to implement. Lots of dragging and dropping. However, there are some 'groups' in the dom, that are sortable, but I need to limit the ability to drag an item past an item with a different class name.

For example, in this Dom, I want the typea items to be sortable amongst themselves, but not be able to mix them in with the typeb or typec items.

I realize that adding more grouping could solve this, however, my actual dom is much more complicated and I'd rather not nest it further with more groups.

JSFiddle Example

<div id="sortable">
    <div class="typea">typea1</div>
    <div class="typea">typea2</div>
    <div class="typea">typea3</div>
    <div class="typea">typea4</div>

    <div class="typeb">typeb1</div>
    <div class="typeb">typeb2</div>
    <div class="typeb">typeb3</div>
    <div class="typeb">typeb4</div>
    <div class="typeb">typeb5</div>

    <div class="typec">typec1</div>
    <div class="typec">typec2</div>
    <div class="typec">typec3</div>
    <div class="typec">typec4</div>
    <div class="typec">typec5</div>
    <div class="typec">typec6</div>
</div>

Upvotes: 0

Views: 1095

Answers (1)

Dom
Dom

Reputation: 40459

You could use sortable's change event, find the class of the placeholder (which will be the same as the original element), and restrict sorting if classes do not match.

$( "#sortable" ).sortable({
    change:function(event,ui){
        var currentClass = $(ui.placeholder)[0].classList[0];
         if(!$(ui.placeholder).prev().hasClass(currentClass) 
            && !$(ui.placeholder).next().hasClass(currentClass))
             return false;
    }
});
$( "#sortable" ).disableSelection();

DEMO: http://jsfiddle.net/dirtyd77/atd8s/1/

Upvotes: 4

Related Questions