Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery UI - How to apply containment to selector that matches multiple divs?

Example:

<div>
    <div class='drop'>
        <div class='drag'></div>
    </div>
    <div class='drop'>
    </div>
    <div class='drop'>
    </div>
    <div class='drop'>
    </div>
    <div>
    </div>
</div>

$('div.drag').draggable({ containment: 'div.drop' });

Normally, if there is only 1 "div.drop" element, it works as intended. If there are more than 1(like in the example above), I thought that it would be dragged/dropped in any of the "div.drop" divs. As it turns out, it is only draggable/droppable to the first element matched by the "div.drop" selector.

Is there a workaround for this(that is, make it contained/droppable/draggable only in the "div.drop" divs)?

EDIT: I guess you are right guys. After some introspection, I realized that I didn't go for your suggested solutions since there are padding between the divs and I don't want the the "div.drag" divs to be dropped on the padded area.

like image 926
developarvin Avatar asked Oct 08 '22 22:10

developarvin


2 Answers

It don't works like that !! The containment is to constraint bound of dragging.

You want drag and drop.
Then you have to configure drag for div.grag:

$('div.drag').draggable();

And configure drop for div.drop:

$('div.drop').droppable();

You can add containment for your drag element with your first div level:

<div id='dragZone'>
    <div class='drop'>
        <div class='drag'></div>
    </div>
    <div class='drop'>
    </div>
</div>


$('div.drag').draggable({ containment: '#dragZone'});
like image 50
Benoît Avatar answered Oct 12 '22 12:10

Benoît


containment restricts the movement of a draggable within the bounds of the given element(s). You could set containment to the parent of the div.drops.

You should make the div.drops droppable, append the draggable on drop, and use the revert: 'invalid' option so that the draggable reverts if it's not dropped on a droppable

$('div.drop').droppable({drop: function(e, ui) {
    ui.draggable.appendTo(this);
}});
$('div.drag').draggable({
    helper: 'clone', 
    revert: 'invalid'
});
like image 24
ori Avatar answered Oct 12 '22 11:10

ori