JQuery fading a div after a certain time

21 January 2009| 7 Comments| Print

Here’s a handy bit of code that I use quite regularly, its particularly useful if your getting a response message from a form to notify the user that there data was sent, or comunicate an error and you want to fade the message out after a set time.

Firstly you  need to include the jQuery framework you can download the latest version here.

All you need to change is the target div, in our case ‘mydiv’

  $(document).ready(function(){
   setTimeout(function(){
  $("div.mydiv").fadeOut("slow", function () {
  $("div.mydiv").remove();
      });

}, 2000);
 });

To adjust the amount of time until the fade function is triggered simply change the ’2000′ to a different number, currently set at 2 seconds or 2000 milliseconds.

demo


Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

7 Comments

  • Joshua (Triscal)

    Hey cool this is like a behind the scenes of DDC lol I if I needed this I sure would use it lol

  • Ashley

    Ha, yeah subscribe to my feed and get the inside gossip! :)

  • Marcus Andersson

    Nice piece of information to get me started! Think it’ll come in handy when confirming, for example, a save when using AJAX.

  • Karl

    Great tip, been looking for something like this for a long, long time.

    Good work :)

  • mark

    Excellent job!

    EXACTLY what i needed.

  • Kevin Rinker

    this is awesome. what if i want somthing to show after a time period?

  • Ashley

    @Kevin you just need to change fadeOut to fadeIn and remove this line $(“div.mydiv”).remove(); your div element will then fade in. :)

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here