multiple droppable

Sune picture Sune · Jun 6, 2010 · Viewed 7.4k times · Source

I've have multiple droppable divs (which all have the same size) and one draggable div. The draggable div is 3 times bigger than one droppable. When I drag the draggable div on the droppables divs I want to find which droppable has been affected.

My code looks like this:

$(function () {

    $(".draggable").draggable({
        drag: function (event, ui) { }

    });
    $(".droppable").droppable({
        drop: function (event, ui) {
           alert(this.id);
        }
    });

}); 

the html

<div style="height:100px; width:200px; border-bottom:1px solid red; " id="Div0" class="droppable">
    drop in me1!
</div>   
<div style="height:100px; width:200px; border-bottom:1px solid red;"  id="Div1" class="droppable">
    drop in me2!
</div>  
<div style="height:100px; width:200px; border-bottom:1px solid red; " id="Div2" class="droppable">
    drop in me2!
</div>  
<div style="height:100px; width:200px; border-bottom:1px solid red; " id="Div3" class="droppable">
    drop in me2!
</div>  
<div style="height:100px; width:200px; border-bottom:1px solid red; " id="Div4" class="droppable">
    drop in me2!
</div>  
<div style="height:100px; width:200px; border-bottom:1px solid red; " id="Div5" class="droppable">
    drop in me2!
</div>  
<div style="height:100px; width:200px; border-bottom:1px solid red; " id="Div6" class="droppable">
    drop in me2!
</div>  
<div style="height:100px; width:200px; border-bottom:1px solid red; " id="Div7" class="droppable">
    drop in me2!
</div>


<div class="draggable" id="drag" style="height:300px; width:50px; border:1px solid black;"><span>Drag</span></div>

But my alert only shows the first which my draggable div (Div0) hits, how can I find the missing (Div1 and Div2), which also is affeckted??

Here's a guy with the same problem : http://forum.jquery.com/topic/drop-onto-multiple-droppable-elements-at-once

Answer

Simen Echholt picture Simen Echholt · Jun 7, 2010

Maybe like this? Put up a demo here.

$(".droppable").droppable({
    drop: function (event, ui) {
        var $draggable = $(ui.draggable);

        var draggableTop    = $draggable.offset().top;
        var draggableHeight = $draggable.height();
        var draggableBottom = draggableTop + draggableHeight;

        $droppables = $(".droppable");

        $droppablesCoveredByDraggable = $droppables.filter( function() {
            var $droppable  = $(this);
            var top                 = $droppable.offset().top;
            var height          = $droppable.height();
            var bottom          = top + height;

            var isCoveredByDraggable = top <= draggableBottom && bottom >= draggableTop;
            return isCoveredByDraggable;
        });

        //example: mark the droppables that are covered
        $droppables.removeClass("marked");
        $droppablesCoveredByDraggable.addClass("marked");
    }
});