JorgeeFG
JorgeeFG

Reputation: 5981

Chaining remove() to fadeOut() avoids animation

Just a simple question.

I have this chain:

$(this).fadeOut(800); //which works good.

Then tried to remove it:

$(this).fadeOut(800).remove(); //makes it remove instantly, without fadeOut effect.

Any help?

http://api.jquery.com/fadeOut/#fadeOut-duration-complete

Upvotes: 0

Views: 116

Answers (5)

PSL
PSL

Reputation: 123739

You want to try using the complete callback function for fadeOut:

$(this).fadeOut(800, function(){
  $(this).remove(); //This will execute once the fadeOut is completed.
});

Probably cache $(this):

 var $this = $(this);
   $this.fadeOut(800, function(){
      $this.remove(); //This will execute once the fadeOut is completed.
    });

Syntax:

.fadeOut( [duration ] [, complete ] )

While invoking the remove() as a chain after the fadeOut() it will get invoked immediately after starting the animation and won't wait for the animation to complete; hence you want to utilize the complete callback to ensure this is done after the animation is complete.

Just to extend the answer with another option using promise() and done()

 var $this = $(this);
 $this.fadeOut(800).css('background-color', 'blue')
                    .promise()
                      .done(function () {
                         $this.remove();
                      });

Demo

Upvotes: 9

ayyp
ayyp

Reputation: 6608

Use $(this).fadeOut(800, function() { $(this).remove(); }); instead. By putting .remove() in a callback, it will only fire once the animation is complete.

Upvotes: 2

David Thomas
David Thomas

Reputation: 253396

Use the callback:

$(this).fadeOut(800, function(){
    $(this).remove();
});

The problem is that the remove() function doesn't wait for the animation to complete, and simply removes the element; whereas using the callback calls the remove() only after the animation is completed.

References:

Upvotes: 3

Adil Shaikh
Adil Shaikh

Reputation: 44740

use fadeOut callback function

$(this).fadeOut(800,function(){
  $(this).remove();
})

Upvotes: 1

Shyju
Shyju

Reputation: 218832

Execute the remove method in the callback of fadeOut method

$(this).fadeOut(800,function(){
  $(this).remove();
});

Upvotes: 2

Related Questions