views:

3575

answers:

5

Hello guys,

I was wondering, how in jquery am I able to hide a div after a few seconds? Like Gmail's messages for example.

I've tried my best but am unable to get it working.

Thanks!

+17  A: 

This will hide the div after 1 second (1000 milliseconds).

setTimeout(function() {
    $('#mydiv').fadeOut('fast');
}, 1000); // <-- time in milliseconds

If you just want to hide without fading, use hide().

swilliams
Thank you very much.
James
A: 

You may want to call

$("div").hide();

in a function which is called in an setTimeout() method.

Niyaz
+1  A: 

Probably the easiest way is to use the timers plugin. http://plugins.jquery.com/project/timers and then call something like

$(this).oneTime(1000, function() {
    $("#something").hide();
  });
stimms
Is there any compelling reason to use the timers plugin over setTimeout or setInterval?
spender
I would say that downloading and attaching a jquery plugin is *less* easy than simply using setTimeout.
Nathan Ridley
I don't think this is necessarily a bad thing, but since it is rare that I ever use timers in my code, having that plugin around (read: extra code, bloat) for those few times does not outweigh the cost. If you were writing a lot of code that needed to use timers, and were using jQuery, I can see why this plugin would be very useful to keep with the jQuery syntax...
Jason Bunting
+3  A: 
$.fn.delay = function(time, callback){
    // Empty function:
    jQuery.fx.step.delay = function(){};
    // Return meaningless animation, (will be added to queue)
    return this.animate({delay:1}, time, callback);
}

From http://james.padolsey.com/javascript/jquery-delay-plugin/

(Allows chaining of methods)

Peter Smit
A: 

Using the jquery timer will also allow you to have a name associated with the timers that are attached to the object. So you could attach several timers to an object and stop any one of them.

$("#myid").oneTime(1000, "mytimer1" function() { $("#something").hide(); }).oneTime(2000, "mytimer2" function() { $("#somethingelse").show();
});;

$("#myid").stopTime("mytimer2");

The eval function (and its relatives, Function, setTimeout, and setInterval) provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript. http://www.jslint.com/lint.html