20

I would like for a div to fadeOut and then be removed:

 $('#div').delay(1000).fadeOut(300);
 $('#div').delay(1300).remove();

Unfortunately, this just directly removes the div, with no delays. Why is it that I can't get the remove action to be delayed? What solutions are there?

Thanks

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
jay
  • 12,066
  • 16
  • 64
  • 103

3 Answers3

39

If you want the element to be removed after it's done being faded out, you can fadeOut's callback parameter.

$('#div').delay(1000).fadeOut(300, function(){
   $(this).remove();
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
7

.delay() only works with methods that go through the animation queue. Thus, it works for .fadeOut() (an animation), but not .remove() (not an animation).

To show you how specialized this is, this doesn't delay:

$('#div').delay(1000).hide();

But, this does:

 $('#div').delay(1000).hide(1);

Putting a duration on the hide method turns it into an animation which then uses the animation queue, which then works with .delay().

To remove the item with a delay, you can use a setTimeout() call:

setTimeout(function() {
    $('#div').remove();
}, 1300);

or get a bit tricky and use a completion function on an animation like this:

$('#div').delay(1000).hide(1, function() {
    $(this).remove();
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 1
    `hide` still keeps the element in the DOM, whereas `remove` doesn't. – gen_Eric Nov 11 '11 at 22:38
  • hmm thanks for your response. Are there delay methods that work with non-animation actions? – jay Nov 11 '11 at 22:38
  • @jay: There's good 'ol `setTimeout`, but other than that, not really. It works for animations because they're in a queue (and it probably uses `setTimeout` anyway). – gen_Eric Nov 11 '11 at 22:41
  • 1
    As far as I know, there are no jQuery delay functions that work with operations outside the queue. You just use setTimeout() for that. I did add to my answer a way of using a completion function on an animation for doing the remove. That lets you use `.delay()`. – jfriend00 Nov 11 '11 at 22:44
  • 1
    @Rocket - read the rest of my answer to see why I was using the .hide() as an example. I'm just explaining how .delay() works or doesn't work. Then, I show a couple of examples that do remove the item. – jfriend00 Nov 11 '11 at 22:46
  • @jfriend00: Ah, ok :-P It's almost time to leave work and my brain is toast. – gen_Eric Nov 11 '11 at 22:47
0

You can try something like this.

$('#div').delay(1000).fadeOut(300,function(){
    setTimeout(function(){
      $('#div').remove()
    } ,1300);

});

I think it works as it should. Hope it helps

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
ZeljkoSi
  • 64
  • 4