[jquery] How to get jQuery to wait until an effect is finished?

I am sure I read about this the other day but I can't seem to find it anywhere.
I have a fadeOut() event after which I remove the element, but jQuery is removing the element before it has the chance to finish fading out.
How do I get jQuery to wait until the element had faded out, then remove it?

This question is related to jquery

The answer is


With jQuery 1.6 version you can use the .promise() method.

$(selector).fadeOut('slow');
$(selector).promise().done(function(){
    // will be called when all the animations on the queue finish
});

You can as well use $.when() to wait until the promise finished:

var myEvent = function() {
    $( selector ).fadeOut( 'fast' );
};
$.when( myEvent() ).done( function() {
    console.log( 'Task finished.' );
} );

In case you're doing a request that could as well fail, then you can even go one step further:

$.when( myEvent() )
    .done( function( d ) {
        console.log( d, 'Task done.' );
    } )
    .fail( function( err ) {
        console.log( err, 'Task failed.' );
    } )
    // Runs always
    .then( function( data, textStatus, jqXHR ) {
        console.log( jqXHR.status, textStatus, 'Status 200/"OK"?' );
    } );

if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.