Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery draggable revert and stop event

First question, so be kind :)

What I am trying to do is call a function when the user releases the draggable, and before the revert animation has completed.

As far as I can see, the stop event is called only when the revert has finished. I have tried passing a function to the revert option of draggable, but it doesn't seem to work. Here is a bit of my code to demonstrate;

$("a").draggable({
    helper:function(){
        return $("<div/>",{id:"mydrag",text:"link"}).appendTo("body");
    },
    revert:function(evt,ui){
        // $("#mydrag").fadeOut("slow");
        return true;
    },
    stop:function(evt,ui){
        console.log("fin");
    }
});

If I uncomment the first line of the revert function - fadeout - then the element fades out but does not revert. The console only logs "fin" when the revert animation has completed.

Can anyone help me? Needless to say I have Googled a lot for an answer, but with no luck.

Buster

like image 620
BusterLuke Avatar asked May 06 '11 12:05

BusterLuke


1 Answers

First, according to this blog, the undocumented revert callback only takes a single argument (the drop socket object, or the boolean false if the drop was rejected).

Now, the problem is that draggable uses animate() internally to reposition the helper. Apparently, that animation gets queued and only starts after your fadeOut effect finishes.

One way to achieve what you want is to perform the call to animate() yourself, like this:

revert: function(socketObj) {
    if (socketObj === false) {
        // Drop was rejected, revert the helper.
        var $helper = $("#mydrag");
        $helper.fadeOut("slow").animate($helper.originalPosition);
        return true;
    } else {
        // Drop was accepted, don't revert.
        return false;
    }
}

That allows the draggable helper to fade out while it's being reverted.

You can test that solution here.

like image 62
Frédéric Hamidi Avatar answered Nov 07 '22 08:11

Frédéric Hamidi