I would like to flash a success message on my page.

I am using the jQuery fadeOut method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.

What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed.

How can you animate this using jQuery?

+11  A: 

use setTimeout(function(){$elem.hide();}, 5000);

Where $elem is the element you wish to hide, and 5000 is the delay in milliseconds. You can actually use any function within the call to setTimeout(), that code just defines a small anonymous function for simplicity.

John Millikin
+3  A: 
var $msg = $('#msg-container-id');
+6  A: 

For a pure jQuery approach, you can do

$("#element").animate({opacity: 1.0}, 5000).fadeOut();

It's a hack, but it does the job

John Sheehan
+7  A: 

While @John Sheehan's approach works, you run into the jQuery fadeIn/fadeOut ClearType glitch in IE7. Personally, I'd opt for @John Millikin's setTimeout() approach, but if you're set on a pure jQuery approach, better to trigger an animation on a non-opacity property, such as a margin.

var left = parseInt($('#element').css('marginLeft'));
    .animate({ marginLeft: left ? left : 0 }, 5000)

You can be a bit cleaner if you know your margin to be a fixed value:

    .animate({ marginLeft: 0 }, 5000)

EDIT: It looks like the jQuery FxQueues plug-in does just what you need:

    speed: 'fast',
    preDelay: 5000
+2  A: 

Following on from dansays' comment, the following seems to work perfectly well:

$('#thing') .animate({dummy:1}, 2000) .animate({ etc ... });

+21  A: 

The new delay() function in jQuery 1.4 should do the trick.

Nathan Long

The first one works best.


dansays's answer just doesn't work for me. For some reason, remove() runs immediately and the div disappears before any animations happen.

The following works, however (by omitting the remove() method):


I don't mind if there are hidden divs on the page (there shouldn't be more than a few anyway).