Bing Bing - 3 years ago 136
Javascript Question

Detecting multiple droppables for a single draggable using jQuery

I'm trying to assign items to people, where the person can take multiple items so long as they can touch/cover them all. In this case, the person is a draggable and the items are droppables.

HTML

<div class="person" data-id="A">Person A</div>
<div class="person" data-id="B">Person B</div>

<div id="item_1" class="droppable" data-id="1">
<input type='hidden' name='value_1' id='value_1' />
Item 1
</div>

<div id="item_2" class="droppable" data-id="2">
<input type='hidden' name='value_2' id='value_2' />
Item 2
</div>

<div id="item_3" class="droppable" data-id="3">
<input type='hidden' name='value_3' id='value_3' />
Item 3
</div>

<br/>

<div id="item_4" class="droppable" data-id="4">
<input type='hidden' name='value_4' id='value_4' />
Item 4
</div>

<div id="item_5" class="droppable" data-id="5">
<input type='hidden' name='value_5' id='value_5' />
Item 5
</div>

<div id="item_6" class="droppable" data-id="6">
<input type='hidden' name='value_6' id='value_6' />
Item 6
</div>


CSS

.yellow {
background-color: yellow;
}
.droppable {
display: inline-block;
margin: 20px 10px;
width: 100px;
height: 20px;
padding: 3px;
border: solid 1px red;
}
.person {
display: block;
width: 350px;
height: 30px;
border: solid 1px black;
}


JS

$('.person').draggable();
$('.droppable').droppable({
hoverClass : "yellow",
drop: function(event, ui) {
$("#value_"+$(this).data("id")).val(ui.draggable.data("id"));
console.log("Item "+$(this).data("id")+" taken by "+ui.draggable.data("id"));
}
});


jsFiddle: https://jsfiddle.net/myingling/66pg1zr1/6/

The problem is, it seems that a draggable can only be dropped upon a single droppable.

How can I make it recognize multiple and assign correctly?

Answer Source

Have a look at the tolerance-option that might help you: https://jsfiddle.net/kgaqb0ay/

$('.droppable').droppable({
    hoverClass : "yellow",
    tolerance: "touch",
    drop: function(event, ui) {
      $("#value_"+$(this).data("id")).val(ui.draggable.data("id"));
      console.log("Item "+$(this).data("id")+" taken by "+ui.draggable.data("id"));
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download