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?
111
votes
4 Answers
188
votes
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
});
174
votes
10
votes
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"?' );
} );