Reputation: 13420
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?
Upvotes: 118
Views: 182268
Reputation: 22333
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"?' );
} );
Upvotes: 10
Reputation: 2487
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
});
Upvotes: 197
Reputation: 650
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.
Upvotes: 6
Reputation: 488394
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
});
Upvotes: 178