Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fadeout and remove an element after a few seconds

Tags:

jquery

fadeout

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.
like image 806
Run Avatar asked Dec 04 '11 14:12

Run


1 Answers

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 );
});
like image 148
Pierre Avatar answered Oct 02 '22 21:10

Pierre