views:

24

answers:

1

Hi, I have a problem with jQuqeryUI. I would like to run some code whenever an element is dragged and dropped on an invalid target. As far as I can see, there is no predefined event for this, but I have thought about combining information from following events: over, out, remove and stop, to achieve this. However that might sound like it's going to be a mess, is there a cleaner way yo do it?

+2  A: 

You can pass a method to the revert option as well, for example if we take the example demo like this:

<div id="draggable" class="ui-widget-content">
    <p>I revert when I'm not dropped</p>
</div>
<div id="droppable" class="ui-widget-header">
    <p>Drop me here</p>
</div>​

Then on your draggable you can calculate whether to revert, like this:

$("#draggable").draggable({ 
    revert:  function(dropped) {
       var dropped = dropped && dropped[0].id == "droppable";
       if(!dropped) alert("I'm reverting, what a cruel world!");
       return !dropped;
    } 
});

You can give it a try here, the dropped parameter passed in is the element it was dropped on that's a .droppable(), it's just false if it landed anywhere else.

Or if you're using the accept option you may want to calculate off that, like this:

var dropped = dropped && $(this).is(dropped.droppable('option', 'accept'));

This uses the accept selector and uses .is() to see if the droppable matches.

You can view a demo of that here.

Nick Craver
Hey thanks for that, it was just what I was looking for.It is a nice undocumented feature ;)
thetrompf
@thetrompf - welcome :)
Nick Craver
Just out of curiosity - where did you find this? I can't find any of this in the manual.
kastermester
@kastermester - The jQuery UI source for `.draggable()`, here: http://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.draggable.js#L199 :)
Nick Craver