views:

393

answers:

3

Is there any way I can get jQuery to perform a function when you drag an item outside a droppable DIV?

Let's say that we have draggable or sortable items in a div and you want them deleted if they are dropped outside their parent div.

I know there is the "out" event but that works as soon as you drag the item outside the div, not when you drop it (release mouse button).

+1  A: 

Why not wrapped all elements with another droppable div, then do the checking there?

What about if the user dropped it outside the browser window? Would you consider this also?

jerjer
I've tried wrapping it in another droppable, but this doesn't seem to work properly no matter what. The "background" droppable event will fire even if I drop inside the "foreground" div where the draggable item was. See http://stackoverflow.com/questions/1491742/jquery-ui-droppable-backgroundBasically I'm still battling the same problem, just got back to trying to fix it.
kasakka
if wrapping will not work for you try stacking, but you must set foreground as a sibling to the background, then just set the appropriate z-index, or if not, CHECK the event.target on the drop callback .. drop: function(e) { if (e.targe.id == bg_id) { ...} else {...} }
jerjer
Tried that, no luck. It seems that the drop function doesn't recognize any other event target id other than the droppable itself. At least when I try to log in the console the id, only the droppable div records, everything else outputs nothing. Likewise using else to go around this doesn't work - it's either do something when dropped on the droppable div or do nothing at all. Unfortunately that doesn't work if the background div fills the whole window, it ignores what's on top of the div
kasakka
A: 

Solved this in a pretty "hacky" way: made a table with a content div in the center and made all other cells of the table droppable. Essentially this means you can drop outside the center div without problems, but it is still far from a good way to do it.

If someone has a better way, please tell me.

kasakka
+2  A: 

Finally got a proper solution to this, even though it is a bit "hacky" as well. What I do is I set the foreground div with the draggables as the droppable, but use the dropover and dropout features to determine if the item is outside the foreground div. When it's outside the div, I bind the mouseup event to do the drop functionality. When it's back in I unbind the mouseup event so it doesn't fire.

Because when dragging I'm already holding the mouse button down, releasing it is the same as dropping what I have in my "hand".

$("#foregroundDiv").droppable({
        accept: ".draggableThingy",
        tolerance: "pointer",       
        out: function(event, ui) {
            $(ui.helper).mouseup(function() {
                doSomethingTo(ui.draggable);
            });
        },
        over: function(event, ui) {
            $(ui.helper).unbind("mouseup");
        }
    });
kasakka