fadeout and remove an element after a few seconds

17,430

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 );
});
Share:
17,430

Related videos on Youtube

Run
Author by

Run

A cross-disciplinary full-stack web developer/designer.

Updated on June 04, 2022

Comments

  • Run
    Run almost 2 years

    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.
    
    • RightSaidFred
      RightSaidFred over 12 years
      Did you by chance notice that your alert() happens before the fadeOut is complete? ;)