views:

48

answers:

3

hey guys,

what's wrong with that?

$('body').append("<div class='message success'>Upload successful!</div>");
$('.message').delay(2000).remove();

I want to append a success message to my html document, but only for 2sec. After that the div should be deleted again.

what am i doing wrong here?

regards

+8  A: 

Using setTimeout() directly (which .delay() uses internally) is simpler here, since .remove() isn't a queued function, overall it should look like this:

$('body').append("<div class='message success'>Upload successful!</div>");
setTimeout(function() {
  $('.message').remove();
}, 2000);

You can give it a try here.

.delay() is for the animation (or whatever named) queue, to use it you'd have to do something like:

$("<div class='message success'>Upload successful!</div>").appendTo('body')
  .delay(2000).queue(function() { $(this).remove(); });

Which works, here...but is just overkill and terribly inefficient, for the sake of chaining IMO. Normally you'd also have to call dequeue or the next function as well, but since you're removing the element anyway...

Nick Craver
@Nick +1 always providing good jquery answers similar to the one you provided for me earlier...
Pandiya Chendur
@Shog9 - To be *completely* accurate it's not *just* animations, it's just *by default* the `fx` queue animations run on, but it can be any queue if passed a name :)
Nick Craver
Woops, deleted that comment since you updated your answer. But you're correct, the queue support is fairly general-purpose, and could be used for other things - the animations just default to it.
Shog9
@Shog9 - I just hope `.delay()` gets some love for queue/animation integration in 1.5, so that a `.stop(true, true)` purges the timeout which isn't stored at all currently...gives some very weird and unexpected side-effects at the moment, something that's not advertised enough IMO.
Nick Craver
@Nick: ouch, I didn't realize that. Good to know...
Shog9
A: 

Maybe I'm using an outdated jQuery, but none of the methods suggested in other answers seem to work for me. According to http://api.jquery.com/delay/ , delay is for animation effects.

Using setTimeout() however, works nicely for me:

$('body').append("<div class='message success'>Upload successful!</div>"); 
setTimeout('$(".message").remove()',2000);
WSkid
Don't pass a string to `setTimeout()`!, pass an anonymous function :)
Nick Craver
A: 

And just for kicks, you could do the following, using delay:

$('body').append("<div class='message success'>Upload successful!</div>");
$('.message').show('fast').delay(2000).hide('fast')
$('.message').remove();
Strelok
That will almost certainly remove the element before it has even been shown...
Shog9
@Shog9. You are right. I just had it working in a jsfiddle ... must have been a different snippet. Weird.
Strelok