Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery draggable, event when dropped outside of parent div

I have a list of photos, and I have draggable added to them, however when the photo is dragged outside of the parent div, I want to change it's class so it indicates that if you drop it, it will be removed, and then when the user drops it, I want it to fire a function. (only if it is outside of the parent div)

<ul class="photos">
<li><img src=""/></li>
<li><img src=""/></li>
</ul>

so when an li is dragged outside of .photos, it fires to add class, and then if it's dropped outside of it, then it fires and event to remove it.

like image 777
Dylan Cross Avatar asked Feb 16 '12 18:02

Dylan Cross


1 Answers

Assuming the parent div you mention is a droppable, you can bind an event handler to the dropout event:

$("#parentDiv").on("dropout", function(event, ui) {
    //ui.draggable refers to the draggable
});

The event will fire any time an accepted draggable is dragged outside the tolerance area of the droppable.

Update (see comments)

You can supply a callback function to the revert option. The function can take one argument which either contains the droppable on which the draggable was dropped, or false (if it was dropped somewhere invalid):

$("#draggable").draggable({
    revert: function(valid) {
        if(!valid) {
            //Dropped outside of valid droppable
        }
    }
});

Here's a working example.

like image 113
James Allardice Avatar answered Nov 09 '22 12:11

James Allardice