10
X

Effect Delay Trick

read 91 comments

Here is a quick trick for getting an effect to delay without using setTimeout.

Let's say, for example, that I want to show an alert message on the page every time a user clicks on a certain button. But I don't want it to stay there forever; I want it to go away a few seconds later. You know, like the way they do in all of those crazy Web 2.0 sites.

Update

In version 1.4, jQuery introduced a .delay() method that allows you to do the same thing as I show below, but without the hack. If you're using jQuery 1.4 or above, definitely use .delay() instead. It takes one argument, the number of milliseconds to delay. Read more about it in the online documentation

Continue Reading Below

The HTML

Well, first I'll need a message, along with a container for it:

HTML:
  1. <div class="quick-alert">Alert! Watch me before it's too late!</div>

Oh, I should also put my button into the HTML—something like this: <input type="submit" id="show-alert" value="Show Alert" />

The CSS

Now I could also use some stylin' for that quick-alert class:

CSS:
  1. .quick-alert {
  2.    width: 50%;
  3.    margin: 1em 0;
  4.    padding: .5em;
  5.    background: #ffa;
  6.    border: 1px solid #a00;
  7.    color: #a00;
  8.    font-weight: bold;
  9.    display: none;
  10.  }

I'll stick that in my stylesheet so that it's ready to be applied to our new, button-generated DIV.

Inserting the Content

On to the code! First, we'll get our message to be inserted when someone clicks on the "Show Alert" button. Let's put the message right after the button, like so:

JavaScript:
  1. $(document).ready(function() {
  2.   $('#show-alert').click(function() {
  3.     $('<div class="quick-alert">Alert! Watch me before it\'s too late!</div>')
  4.     .insertAfter( $(this) );
  5.   });
  6. });

So, basically, what I'm saying here is, upon clicking the <input id="show-alert" /> button, create this div with the class and all the text inside of it, and place it right after the button. Notice the backslash in "it\'s." That keeps jQuery from getting confused That escapes the single quote, which is necessary because otherwise — as Dave Cardwell explains in his comment — "the JavaScript parser would interpret that as the close of the string."

Adding the Effects

So far, so good. Now I'm going to add my .fadeIn() and .fadeOut() effects. And after those are done, I'll remove the div that I just created. No sense keeping it around:

JavaScript:
  1. $(document).ready(function() {
  2.   $('#show-alert').click(function() {
  3.     $('<div class="quick-alert">Alert! Watch me before it\'s too late!</div>')
  4.     .insertAfter( $(this) )
  5.     .fadeIn('slow')
  6.     .fadeOut('slow', function() {
  7.       $(this).remove();
  8.     });
  9.   });
  10. });

Because I put $(this).remove() in the callback of the .fadeOut() method, it occurs after the the fading out is finished.

The Delay

So, here's the thing. The entry's title says that this is a trick, right? Well, I hope it's not a dirty trick, but here goes the full code:

JavaScript:
  1. $(document).ready(function() {
  2.   $('#show-alert').click(function() {
  3.     $('<div class="quick-alert">Alert! Watch me before it\'s too late!</div>')
  4.     .insertAfter( $(this) )
  5.     .fadeIn('slow')
  6.     .animate({opacity: 1.0}, 3000)
  7.     .fadeOut('slow', function() {
  8.       $(this).remove();
  9.     });
  10.   });
  11. });

Do you see that .animate() method there? I have it animating to a full opacity in 3 seconds. But the div is already at full opacity, so it just sits there looking like it's doing nothing for 3 seconds. Isn't that cute?

Here you go. Try it out for yourself:

I hope you enjoyed the message while it lasted!


comment feed

91 comments

  1. omg. Thats just what I've been looking for, thank you!

  2. teemu

    now that was cool and simple, thanks!

  3. Neil

    Nice stuff Karl,

    As an added bonus, you can click the button several times and see mesages appearing and fading out one after the other !

    Neil

  4. Neil

    Karl,

    Firefox 1.5.0.7 - brilliant!
    Firefox 2.0.01 - brilliant!
    IE 7 - brilliant!

    Just thought I'd let you know a couple of bugs I noticed:

    All on Win XP Pro

    IE 6 SP2 - message didn't fade in or out
    Firefox 1.0.8 - message flicker at end of fade in and beginning of fade out
    Opera 9.10 - slight "shift" in the text upon complete fade in
    Netscape 7.2 - message flicker at end of fade in and beginning of fade out
    Netscape 8.1.2 - message flicker at end of fade in and beginning of fade out

  5. Thanks for the browser testing, Neil! Oddly, I just tried it in IE 6 SP2, and the fades were working properly. I don't have the version of Firefox/Netscape that produced bugs, but I'll take your word for it. :) The Opera bug is a little disconcerting. It might have to do with the way jQuery calculates the height of the div before fading it in. I'll have to install Opera on my machine and give it a whirl. Thanks again!

  6. Notice the backslash in "it's." That keeps jQuery from getting confused.

    The reason you need the backslash is because otherwise the JavaScript parser would interpret that as the close of the string, not for jQuery's sake.

    Nice tip and write up - Jonathan Howard's Pause plugin performs a similar function.

  7. Thanks, Dave, for the clarification. You're right, of course. It was late, and I was too tired to think about what I was writing at that point. Should have waited for the clear light of dawn, as they say. :) Thanks, too, for the link to the pause plugin. Cheers!

  8. @Karl:

    I would think Dave's recommendation of a pause() plug-in would be a more elegant and efficient method of doing this. The animate() method is going to be wasting some processing--as it will attempt to animate the layer (i.e. the flicker effect.)

    At least the pause plug-in does exactly what you want w/no extra overhead.

  9. @Dan,
    Yep, you're absolutely right. This entry was meant more as a quick (and dirty) trick, emphasis on the trick. :) (I've got to stop using these emoticons!) Certainly not a "best practice." A more elegant solution would use setTimeout, which Jonathan's does, and which I mention in the first paragraph. That said, I checked CPU usage while running this, and the impact — on my machine at least — was negligible. Still, I really appreciate the comment. It never hurts to reinforce these things.

  10. Erin

    Help me understand: On line 4 'this' refers to the button being clicked but on line 8 'this' refers to the div. Why? and when did it change?

  11. Erin

    Opera 9.10 (Mac) looks fine to me.

  12. choan

    Erin,

    In line 4, we're inside the event handler for the click event of #showAlert. this points to that element.

    In line 8, we're inside a function that acts as a callback for the finished effect, so this refers to the element which has been animated.

    HTH.

  13. choan

    Uh, that last comment was mine, not Erin's.

  14. Fixed! :)

    And thanks, Choan, for explaining this to Erin.

  15. Benjamin

    I`ve changed it a bit to make this work with a text-link without getting moved to the top of the page.
    It works for me, but being totally new to Jquery I dont know if the code is correct, but hey...it works :)

    I really love your tutorials keep them coming :)


    $(document).ready(function() {

    $('#quick-alert').hide();

    $('a#show-alert').click(function() {
    $('#quick-alert').fadeIn('slow')

    .animate({opacity: 1.0}, 6000)
    .fadeOut('slow', function() {
    $(this).remove();

    });
    return false;
    });
    });

  16. Well done, Benjamin. That's exactly what you need to do — add return false to the .click() handler.

  17. Neil Merton

    Hi Karl,

    Great website - it's been a tremdous help. I would like to incorporate this idea but instead of it being activated by a button I would like it to trigger when the page loads. I.e. when the page loads it displays the message for xx seconds and then the message disappears.

    Any ideas?

    Many thanks, and keep up the great tutorials!

  18. Hi Neil,

    So glad you like the tutorials! For triggering on page load, you might want to just use window.setTimeout(). Say you want to show <div id="temp">temporary message</div> for 3 seconds when the window loads. You could do something like this:

    var removeTemp = function() {
      $('#temp').remove();
    };
    window.setTimeout(removeTemp,3000);

    Hope that helps!

  19. Neil Merton

    Hi Karl,

    Thanks for the reply - here's what I went with:

    var removeTemp = function() { $('#message').fadeOut('slow', function() { $(this).remove(); }); };
    window.setTimeout(removeTemp,3000);

  20. What about a delay before any effect takes place in order to take advantage of implementing this with other scripts and effects?

  21. Hi John, I'm not sure I'm understanding your question correctly, but I think it's just a matter of where you position the delay in your code, whether it's the "trick" or the setTimeout().

  22. Hello I'm new to the jQuery world and new to JavaScript. I'm looking to use the "Delay Trick" for an in-page massage, but I only want the message to appear on the first click and not reoccur.

    Or better yet to display something different on an additional click.
    I was wondering if any one out there has tackled this one.

  23. Hi Mike,

    If you only want to trigger an event one time, you can take advantage of jQuery's .one('event', fn) method.

    If you want to display something different on additional clicks, try something like this:

    $(document).ready(function() {
      var $foo = $('<div id="foo"></div>')
        .hide()
        .prependTo('body');
      var warnings = 0;
      var warningMsg = 'Welcome to the click event!';
      $('#set-warning').click(function() {
        if (warnings) {
          warningMsg = 'you have clicked this link ' + (warnings + 1) + ' times!';
        };
        $foo.html(warningMsg).animate({opacity: 1}, 2000, function() {
          $foo.slideUp('fast');
        });
        warnings++;
        return false;
      });
    });

    This creates a div element with id="foo" when the DOM is ready, hides it, and inserts it at the beginning of the body. Then it sets a counter and changes the message based on whether the counter is at 0 or more than 0. As for the rest, well, it's pretty much the same as what I wrote about in the entry.

    Hope that helps.

  24. Alex

    Hi Karl,

    I'm trying to use your delay trick to reposition a background-image position, delay the animation for a split second, then return the background-image to it's original position -- but getting no love.

    $("#flip")
    .css("background-position", "top right")
    .animate({opacity:1.0}, 3000)
    .css("background-position", "top center");

    Is my thinking flawed here?

  25. Hi Alex,

    The problem is that this trick only works with jQuery's effects (slideUp, fadeIn, etc.), not with your standard css manipulation, because it takes advantage of jQuery's built-in queuing of effects. For delaying something like background position, I'd recommend using a setTimeout(), as I describe in comment 18 above. Let me know if that works for you.

  26. Alex

    Thanks Karl,

    Yes, that's what I thought. Was hoping there might be a more jQuery-like method to pull it off.

    Do you imagine CSS manipulations ever being added to jQuery's animation queue (or have their own queue)? The ability to pause between chained CSS instructions would seem to open up a huge potential for animation without adding a massive overhead to the library (I'm guessing there).

  27. Luis Filipe

    Seems like this effect delay trick is not working so well with jquery 1.2

  28. Hi Luis,

    I just put up a test page with the script from here, and it seems to be working fine.

    Please have a look and see if it causes any problems for you:
    effect delay test

    Thanks.

  29. Luis Filipe

    Weird... It's working fine now.

  30. Poxline

    Very nice alert effect !

  31. Nick

    I've been playing around with it for a bit, but i'm new to javascript and am having no luck. I have a div with a text link in it, when someone clicks it, I want the alert to appear in another div right below that one, and push everything below it down. Right now, the alert appearing on top of the div with the link it it(as in, the alert hovers over the div), just a pixel or two below the link. How would I fix this? Is it possible to place the div somewhere on the page, and have the link that calls the alert somewhere else on the page? it's only appearing right below the link/button. Sorry, again I'm new.

  32. Nick

    http://www.muttmansion.com/lightbox/fader/

    I found this page which displays a similar alert effect, but doesn't remove the div once it's been placed in the page, it just fades the opacity, leaving the space it occupied when visible. It uses ajax though, to fetch a seperate page for the alert box. and no matter where the button is at, in the page, it will always display the alert inside the same box.. whereas yours only displays it directly below the button.(if I did it right)

    I'm trying to find/make/get a script that will display the message(grabbed from another file(ajax)) in a div, and no matter where I have the button at, always have the messages displayed inside that div, not directly under the button. I want it to act like yours, in that it removes the space where the div occupied when it was visible, after it disappears.

    could you point me in the right direction?

  33. benant

    That's a great trick and simple!! Thanks.

  34. benant

    That's great trick and simple !! Thanks.

  35. When I found this article, I was looking for a lightbox script with a fader but I'm glad I came across this because I wasn't familiar with JQuery library. Within 10 minutes of reading this article I was using JQuery library and the example here was a great start for somebody already familiar with JavaScript and coding to show the basic power of this great tool.

    Thanks for the article !!

  36. Great, I have adapted to perform some additional tasks :
    $('#dirConnect a#noframe').click(function (e) {
    e.preventDefault();
    var answer = $('#url_connex');
    if (answer.is(':visible')){
    answer.slideUp(400);
    //alert("La fenêtre de connexion est fermée");
    $('#connect_msg').html("La fenêtre de connexion est fermée").css({ border:"1px solid red" ,color:"red" }).insertAfter( $(this) ).fadeIn('slow').animate({opacity: 1.0}, 3000).fadeOut('slow');
    }else{answer.slideDown(400);
    //alert("La fenêtre de connexion est ouverte");
    $('#connect_msg').html("La fenêtre de connexion est ouverte").css({ border:"1px solid orange" ,color:"orange" }).insertAfter( $(this) ).fadeIn('slow').animate({opacity: 1.0}, 3000).fadeOut('slow');
    }
    return false;
    });

  37. exelente plungin, muchas gracias, saludos desde Chile!!

  38. Florian

    Cool Trick :)

    Do you have a tip for me how to modify this a little bit?

    I have a dropdown menu. Do open it I have to click a link which I defined:

    $("a.btn_options_bar").click(function () {
    $("div.menu_options").slideToggle("normal");
    $("a.btn_options_bar").toggleClass("btn_options_bar_act");
    });

    So, clicking on the button slides down the menu and sets the button to active
    status. Clicking again sets everything back. The menu consists of an div > .menu_options
    within this div there is a list (ul/li).
    To close the menu you have to click again. But I also want to hide the menu when I move
    out of the ul/li area after 1 sec. Hence I tried something with mouseout but the event starts at
    once. Any idea how to realize that kind of functionality?

    thanks indeed!

  39. Hi Florian,

    To get that to work, you'll need to use a standard JavaScript setTimeout() method. Or, you could take a look at the hoverIntent plugin:
    http://cherne.net/brian/resources/jquery.hoverIntent.html

  40. pig23

    that's great

  41. Its perfect and cool... i like it :)

  42. Hi :)
    I try to use Jonathan Howard's Pause plugin http://blog.mythin.net/projects/jquery.php in jQuery hover function. For example if I leave cursor from div I would like to have small delay before the function chcange div. I put in code pause() but it doesn't work, because there is no action after setted time. Could somebody help me ?

  43. Hi Paweł,

    I'd suggest using Brian Cherne's hoverIntent plugin instead.

  44. Hi :)
    may be it's good plugin, but still have some problem. As Brian show some examples, I need more options [I write about Brian's demo] If user move mouse out from one <li> to next <li> I need timeout: 0, but if user move mouse out from #demo3 to other place of site I need higher timeout. I think it would be to complicated to do this by jQuery and I must use only JavaScript with setTimeout function

  45. num

    I've found issues with jQuery 1.2.6 using this 'opacity' pause feature with overlapping absolute positioned DIV's with background images in IE7 even. The 'opacity' causes the overlapping portion of the background to flicker and be washed out. I use other integer-based CSS values for this pause feature such as:

    $('#myDiv').css('borderWidth',0).animate({'borderWidth':0}, 2000).animate({'opacity':0}, 200, function() { $(this).remove(); });

    ... for a delayed fadeout of myDiv.

  46. tkabbs

    I have relpaced the animate() with a fadeto(), and it seems to work pretty consistantly.
    Basically fading from 1.0 opacity to 1.0 opacity, and using the delay to set the timeout then the callback.

  47. Nice idea. However, that assumes the opacity value is set to 1. Beginning with jQuery 1.2, you can use relative values in the animate() method. Instead of {opacity: 1.0}, you can just use {opacity: '+=0'}. As other mentionned here, you can also use some other information, like {borderWidth:'+='} for better interoperability.

  48. IMO that's better solution for pause efect

    function pause(numberMillis)
    {
    	var now = new Date();
    	var exitTime = now.getTime() + numberMillis;
    	while (true)
    	{
    		now = new Date();
    		if (now.getTime() > exitTime)
    			return;
    	}
    }
    
  49. Paul Giblock

    Please, nobody take KLUSEK's advice above. A function that does a busy loop just to delay is totally wrong and irresponsible programming! Why tax the users' computer when it is supposed to idle. that is what setTimeOut is for. At least put a delay in your loop!!!

  50. Si

    A wicked little snippet. The genius is in its simplicity. thanks

  51. Babu

    Hi,
    Fading is not happening when used with the form

  52. Ronald

    I have a cool JQuery Text Effect.. I thought of transforming first all characters inside a tag, then individually animating each.. so here's an example:

    Sample 1
    Sample 2

    Scatter.. :D Soon to create a jquery function for it.. but I don't know how.. I'm learning though :D

  53. hello, i was looking for jquery effect queue. your tutorial helped me. i was not aware of the callback function of fade*.

    thanks a lot.

  54. Simon

    Great trick! Helped me out a lot, thanks again!

  55. Ali

    You saved my day, thanks!

  56. lenin

    Very nice, thanks

  57. Great trick, thanks. Unfortunately for me I was really needing a way to pause before running a plugin but this has worked. Any ideas? Thanks in advance.

  58. Why write a post about a "trick" when the actual solution is already out there and works perfectly for what you are trying to accomplish? Not trying to bash the original intent, to use jQuery creatively, but it seems strange to me.

    • @Chris - This was posted over two years ago. maybe there wasn't a solution then?

      • JavaScript's setTimeout has always been available. Still, this trick — and it is a trick — can be quite convenient when you're chaining methods together. Using setTimeout can sometimes break the flow of the script (not the actual behavior, just the way the code itself looks). Whatever. Chris, if you feel confident using setTimeout, then by all means keep using it.

  59. phicarre

    How to center the message in the middle of the screen whatever the browser ?

  60. Nic

    Very sleek, thx!

  61. AnzeT'o

    Hey!

    I was doing everything like you said, but something goes wrong. I'm trying to put this code on a site, which is loaded after successful logging ... so that user receives nice warm welcome hello!

    Code in "head":

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
    $('#welcome-alert').click(function() {
    $(<div class="welcome-alert">Alert! Watch me before it is too late!</div>)
    .insertAfter( $(this) )
    .fadeIn ('slow')
    .animate ({opacity: 1.0}, 3000)
    .fadeOut('slow', function() {
    $(this).remove();
    });
    });
    });
    </script>

    Code somewhere on page:
    <?php
    if ($_GET['makewelcome'] == "true") {
    echo "<input id=\"welcome-alert\" type=\"submit\" value=\"effect delay\" />";
    }
    ?
    >

    I've tried to do it with button, what makes no sense (because apparently admin won't click the button to say hello to him :)), but it doesn't work.

    Is there anything wrong with my code? Please give me some hints, jQuery is something totally new for me ... :S

    Thanks for ur time and help!

  62. ZQ

    man! i love you! xD Delay is what i just needed :D U RLZ

  63. Martin

    Brilliant in simplicity. Thank you!

  64. Nice little trick, works like a charm

    Thank you
    K.

  65. Great, that opacity-animate trick!

    I used slideUp and slideDown to separate a big form into animated parts. Those parts are of different length. There is an absolutely positioned footer at bottom of the page as well. In IE6 the footer positiones itself less or more relative to the slided-up form. This would cause that the footer overlaps the slided-down form when it is longer than the slided-up form :(

    After a long time of searching I found your genious opacity-animate trick so that I could fix this IE6 specific misbehaviour with just the following function:

    
    $.stickFooter = function(time) {
    	if ($.browser.msie && $.browser.version == 6) {
    		$('#footer').animate({opacity: 1.0}, time);
    	}
    }
    

    (where time is obviously the slide-up time)

  66. thanks for the tip!

  67. Great delay! Thanks so much for posting this.

  68. Travis

    Awesome! Much nicer than setTimeout.

    • Jp

      Why not a plugin like

      /**
      * Delay plugin inspired by learningjquery.com/2007/01/effect-delay-trick
      * @author : Jp Siffert
      * @param :  delay interval, if not given default to 1000ms
      * @return : jquery chain object
      **/
      
      $.fn.delay = function(delay){
          if(typeof delay==="undefined")  delay = 1000;
          return this.animate({void:0}, delay);
      }
      
      

      This way you can call it like this

      
          $('#element').delay().effect('pulsate');
      
      

      Thanks anyway!

  69. Jp

    Why not a plugin like (small correction void should be a string)

    /**
    * Delay plugin inspired by learningjquery.com/2007/01/effect-delay-trick
    * @author : Jp Siffert
    * @param : delay interval, if not given default to 1000ms
    * @return : jquery chain object
    **/

    $.fn.delay = function(delay){
    if(typeof delay==="undefined") delay = 1000;
    return this.animate({"void":0}, delay);
    }

    This way you can call it like this

    $('#element').delay().effect('pulsate');

    Thanks anyway!

  70. Fantastic work. I've just been fiddling about with jQuery trying to get a 'border-top' on a menu to slide across as you hover, which I've finally managed to do. This worked wonders when I wanted to slightly delay the return to the original menu item!
    Thanks a million!
    Jamie

  71. Rob

    Great article! I've just added a similar thing to one of my recent projects using the uploadify plugin.

  72. Alberto

    Wow! A simple solution, great workaround ;)

  73. ....and.... perfectly explained

  74. $("thing")fadeTo("slow",1,function(){$(this).css("color","#333")});

    that's how i got around the timer problem, just fade to full opacity and then a callback for whatever you want.

    • great example and explanation.

      I'm adapting this as a way to prevent doubleclicking a submit button, without locking down the button permanently, because we have validation on the form, so it may need to be resubmitted.

      
      $(document).ready(function() {
      		$(':submit').click(function() {
      			$original = $(this).val();
      			$(this).val('Saving, please wait...')
      			.attr("disabled","disabled")
      			.fadeIn('slow')
      			.animate({opacity: 0.4}, 4000)
      			.fadeIn('slow', function() {
      				$(this).val($original).removeAttr("disabled").animate({opacity: 1}, 2000)		
      			});
      		});
      });
      

      my problem is that it's conflicting with the Jquery validation plugin: prevents it from showing its error spans.

  75. Tobz

    This doesn't seem to work in IE8, I had to put the tag below in:
    <META HTTP-EQUIV="X-UA-Compatible" CONTENT="IE=7">

    Is there a fix? Really like the code, thank you...

  76. Hi. I always made like so :

    .fadeIn("medium", function() { setTimeout("$j('#comwarning').fadeOut('slow')", 3000) } );

    A little less jQuery-likely, but contained in one line :)

    See you

  77. Ant

    You have something wrong in code:
    $('<div class="quick-alert">Alert! Watch me before it\'s too late!</div>')

    You should type it’s, not it's. ’ is not single quote. Qutes used for, uh, quotations. It’sapostrophecalled apostrophe.

    • Seriously? You consider that a mistake in the code? I might grant you that it's a typographical mistake, but it hardly warrants a mention here. By the way, tell me if you can see any difference between this:
      '
      and this:
      '

      I can't. Now view source. The second one uses &apos;, which as far as I can tell, is meant for apostrophes.

      Anyway, thanks for this little diversion.

  78. why use all of this jquery when you can have the same result using this?

    JQuery

    
    $(document).ready(function(){
    $("#show-alert").click(function(){
    $("#quick-alert").fadeIn("slow").fadeOut(3000);
    });
    });

    HTML

    
    ->Button with and id of "show-alert" here<--
    
    Alert!Watch me before its too late!

    CSS

    
    #quick-alert {
     width: 150px;
    height:60px;
       padding: .5px;
       background: #ffa;
       border: 1px solid #a00;
       color: #a00;
       font-weight: bold;
       display: none;
    }

    Just wondering why,would be really thankful if someone answers this.
    Its like you can head to the supermarket by following road 1 which is full of corners ,when you can use road 2 which is a straight line.

    • Hi Nick,

      I'm not really seeing how your solution offers any improvement, and it certainly doesn't have the same result unless you assume that the message is in the HTML to begin with. But to answer your question, the additional jQuery that I propose above has two parts:

      1. Insertion/removal of the element. Often this kind of content doesn't really belong in the HTML, so inserting it dynamically and then removing it after the message is displayed for a while seems (to me at least) like a reasonable thing to do.
      2. The delay. I much prefer having a message remain fully visible for a time over having it fade out as soon as it has finished fading in. Chaining a .delay() method, or even using the .animate() trick, is trivial in terms of both the extra code and the extra time it takes to write it.

      So, let's say for the sake of argument that we do already have the message in the HTML. The script I initially proposed would look like this:

      $(document).ready(function() {
        $('#show-alert').click(function() {
          $('div.quick-alert')
          .fadeIn('slow')
          .animate({opacity: 1.0}, 3000)
          .fadeOut('slow');
        });
      });
      

      Or, as of jQuery 1.4:

      $(document).ready(function() {
        $('#show-alert').click(function() {
          $('div.quick-alert')
          .fadeIn('slow')
          .delay(3000)
          .fadeOut('slow');
        });
      });
      

      The only extra code is in bold — which makes your supermarket analogy seem like a stretch at best.

      • Thanks for your answer Karl. :)
        Will keep these things in mind :)

        Btw i added the delay function and achieved a closer result.

        $(document).ready(function(){
        $("#show-alert").click(function(){
        $("#quick-alert").fadeIn(30).delay(3000)fadeOut(10);
        });
        });
        • Hey Nick,
          No problem. I hope my reply wasn't worded too strongly. Your idea was on the right track, and it's always a good idea to consider how we can simplify things, but it I don't think it quite applied to this situation. Keep up the good work!

10 Pings

  1. La Fuente » JQuery: Sistema de errores

    [...] Otra forma de hacer esto mismo es utilizando el siguiente código (http://www.learningjquery.com/2007/01/effect-delay-trick): [...]

  2. jQuery Eklentileri | Bir Öğrenci Klasiği

    [...] jQuery Puffer. jQuery iFrame Plugin. Cookie Plugin for jQuery. jQuery Spy - awesome plugin. Effect Delay Trick. jQuick - a quick tag creator for jQuery. Metaobjects. [...]

  3. jQuery Eklentileri | Bir Öğrenci Klasiği

    [...] jQuery Puffer. jQuery iFrame Plugin. Cookie Plugin for jQuery. jQuery Spy - awesome plugin. Effect Delay Trick. jQuick - a quick tag creator for jQuery. Metaobjects. [...]

  4. 这个…..名字还没想好 -_-|| » 240多个jQuery插件

    [...] jQuery Puffer. jQuery iFrame Plugin. Cookie Plugin for jQuery. jQuery Spy - awesome plugin. Effect Delay Trick. jQuick - a quick tag creator for jQuery. Metaobjects. [...]

  5. srui’s blog » 240多个jQuery插件

    [...] jQuery Puffer. jQuery iFrame Plugin. Cookie Plugin for jQuery. jQuery Spy - awesome plugin. Effect Delay Trick. jQuick - a quick tag creator for jQuery.Metaobjects. [...]

  6. [...] jQuery Puffer. jQuery iFrame Plugin. Cookie Plugin for jQuery. jQuery Spy - awesome plugin. Effect Delay Trick. jQuick - a quick tag creator for jQuery. Metaobjects. [...]

  7. [...] jQuery Puffer. jQuery iFrame Plugin. Cookie Plugin for jQuery. jQuery Spy - awesome plugin. Effect Delay Trick. jQuick - a quick tag creator for jQuery.Metaobjects. [...]

  8. [...] jQuery Puffer. jQuery iFrame Plugin. Cookie Plugin for jQuery. jQuery Spy - awesome plugin. Effect Delay Trick. jQuick - a quick tag creator for jQuery. Metaobjects. [...]

  9. [...] jQuery Puffer. jQuery iFrame Plugin. Cookie Plugin for jQuery. jQuery Spy - awesome plugin. Effect Delay Trick. jQuick - a quick tag creator for jQuery. Metaobjects. [...]

Sorry, but comments for this entry are now closed.