fadeout and remove an element after a few seconds

laukok picture laukok · Dec 4, 2011 · Viewed 17.2k times · Source

Why the element cannot be removed in the callback of $.fadeout?

For instance,

$(".background-blackout").fadeOut('slow', function(){
    // Remove all the layer.
        $(this).remove();
}));


alert($('.background-blackout').length);
// return 1

This works without the callback,

$(".background-blackout").fadeOut('slow', function(){

}).remove();

alert($('.background-blackout').length);
// return 0.

But it removes the element before the element has fully faded out. So I think I should call the remove() after a few seconds?

So how can I do that with remove()?

I tried with this but the layer won't be removed,

$(".background-blackout").fadeOut('slow', function(){
});


setTimeout(function(){
    $(".background-blackout").remove(); 
},2000);


alert($('.background-blackout').length);
// returns 1.

Answer

Pierre picture Pierre · Dec 4, 2011

You got it almost right, however you need to test the element's existence inside the callback, as follows:

$(".background-blackout").fadeOut('slow', function(){
  $(this).remove();
  // alert( $('.background-blackout').length );
  console.log( $('.background-blackout').length );
});