How To Fade Out And Remove A Div After Certain Time in jQuery

Tuesday, August 23, 2011

Here’s a handy bit of code that I use often. Sometime you need to notify user about something and after some time it is needed to be removed. At such time, jQuery’s this snippet is sure shot work. Time after you have to remove is passed in milliseconds. For 1 second, you have to pass 1000. After that time, first fading out occurs followed by removing that from DOM.
jQuery(document).ready(function($){
 setTimeout(function() {
   $('#div-to-remove').fadeOut('slow',function(){
    $('#div-to-remove').remove(); 
   }); 
 }, 5000); 
});  
In this example, the div with id ‘div-to-remove’, will be faded out and removed in 5 seconds.

3 comments:

Yash Mistrey [Reply] said...

but after refreshing the page it'l display again ? how to remove it or hide after a certain time.

actually i am building a news site. i created a breaking news section called # "prime_news" i want to show it only for few hours after publish the post. like this http://www.firstpost.com/

Nilambar Sharma [Reply] said...

@Yash MistreyTo show it for few hours, I think you need to use cookies to save first displayed time and check that time to display later. On the other hand why dont you try server side to display news?

javedahmed sheikh [Reply] said...

i want once it is removed after 5 second then it will never show again.

Post a Comment

 
back to top