Making an element disappear with a certain delay is something that should be avoided whenever it's possible when defining user interfaces, because delaying an action may cause several problems to user interaction. Instead, this kind of effect is really useful when it comes to pure jQuery animations. Let's see how to implement this use case.
We can use the setTimeout()
function combined with the animation queue. Here's a simple plugin:
(function($) { $.fn.fadeDelay = function(delay) { var that = $(this); delay = delay || 3000; return that.each(function() { $(that).queue(function() { setTimeout(function() { $(that).dequeue(); }, delay); }); $(that).fadeOut('slow'); }); }; })(jQuery);
fadeDelay()
accepts as its sole parameter the number of milliseconds to be passed to the setTimeout()
function. An example:
$('#test').fadeDelay(4000);
You can see the demo below.