Question

I am looking for an example of drag and drop where the drag item has two distinct areas that have to match up with two droppable areas.

Example: alt text

I would like the blue drag item to revert unless it is dropped in a position where each of its red children land on a green area.

Ideally I would like to use jquery ui (as I have experience with it), but any javascript library would be fine, thanks in advance.

Was it helpful?

Solution

You can accomplish this by using a combination of draggable/droppable options. Given HTML like this:

<div id="blue" class="valid">
    <div id="red-one" class="red"></div>
    <div id="red-two" class="red"></div>
</div>

<div id="green-container">
    <div id="green-one" class="green">
    </div>
    <div id="green-two" class="green">
    </div>
</div>

(omitting CSS, I did add some rules, see in the fiddle below).

You can write JavaScript like this:

function isInside(one, other) {
    return one.offset().left >= other.offset().left &&
        one.offset().top >= other.offset().top &&
        one.offset().top + one.height() <= other.offset().top + other.height() &&
        one.offset().left + one.width() <= other.offset().left + other.width();
}

$("#blue").draggable({
    drag: function(event, ui) {
        var $this = $(this);
        var $reds = $this.children(".red");
        var $greens = $("#green-container").children(".green");
        var firstRed = $reds.first();
        var firstGreen = $greens.first();
        var secondRed = $reds.last();
        var secondGreen = $greens.last();

        if (isInside(firstRed, firstGreen) && isInside(secondRed, secondGreen)) {
            $this.addClass('valid');
        }
        else {
            $this.removeClass('valid');
        }       
    },
    revert: 'invalid'
});


$("#green-container").droppable({ accept: ".valid" });

Check it out here: http://jsfiddle.net/andrewwhitaker/g6FKz/

Notes:

  • For some reason I had to apply the 'valid' class initially to the 'blue' div, or else the target droppable would not accept the dragged element, even if it was valid (would appreciate some input on this). Not sure what's up with that, might be a bug in jQueryUI. Not a huge deal though.
  • The target droppable isn't exactly the two green elements, it's a white div that contains those elements. This should be clear from the example.
  • Every time you move the draggable div, the "drag" event is called, which determines if the red boxes are inside the green ones and assigns a valid class to the draggable div. The droppable object only accepts valid draggables.

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top