Hide div after a few seconds

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.



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

setTimeout(function() {
}, 1000); // <-- time in milliseconds
    width: 100px;
    height: 100px;
    background: #000;
    color: #fff;
    text-align: center;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">myDiv</div>

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


jquery offers a variety of methods to hide the div in a timed manner that do not require setting up and later clearing or resetting interval timers or other event handlers. Here are a few examples.

Pure hide, one second delay

// hide in one second

Pure hide, no delay

// hide immediately

Animated hide

// start hide in one second, take 1/2 second for animated hide effect

fade out

// start fade out in one second, take 300ms to fade

Additionally, the methods can take a queue name or function as a second parameter (depending on method). Documentation for all the calls above and other related calls can be found here: https://api.jquery.com/category/effects/

$.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)


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() {
}).oneTime(2000, "mytimer2" function() {


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.



we can directly use


You can try the .delay()


call the div set the delay time in milliseconds and set the property you want to change, in this case I used .fadeOut() so it could be animated, but you can use .hide() as well.



There's a really simple way to do this.

The problem is that .delay only effects animations, so what you need to do is make .hide() act like an animation by giving it a duration.


By giving it a nice short duration, it appears to be instant just like the regular .hide function.


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() {
      $(function() {

<div id="hide-it">myDiv</div>


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.