How to get jQuery to wait until an effect is finished?

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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
});

Solution 2 - Jquery

You can specify a callback function:

$(selector).fadeOut('slow', function() {
    // will be called when the element finishes fading out
    // if selector matches multiple elements it will be called once for each
});

Documentation here.

Solution 3 - Jquery

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"?' );
    } );

Solution 4 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionuriDiumView Question on Stackoverflow
Solution 1 - JqueryReinaldo JuniorView Answer on Stackoverflow
Solution 2 - JqueryPaolo BergantinoView Answer on Stackoverflow
Solution 3 - JquerykaiserView Answer on Stackoverflow
Solution 4 - JquerySaminView Answer on Stackoverflow