tags:

views:

608

answers:

2

I have a div at the top of a page that I would like to fade in and out 3 times. I found a question/answer already that shows how to fade with an infinite loop by putting the fade effects in a function that calls itself, but I was wondering what the best way to specify a finite number of fade cycles. So far, this is what I have (stolen from another StackOverflow post):

function fade() {
        $("#notification").animate({opacity: 1.0}, {duration: 500})
            .animate({opacity: 0}, {duration: 500})
            .animate({opacity: 0}, {duration: 500})
            .animate({opacity: 1.0}, {duration: 500, complete: fade})
    }

Apologies in advance for being such a js noob.

+5  A: 

If you are using the latest version of jQuery (1.4 as of this writing), you can specify such a short cycle with straight function calls:

$("#notification").fadeIn(500).fadeOut(500).delay(500)
                  .fadeIn(500).fadeOut(500).delay(500)
                  .fadeIn(500).fadeOut(500);

delay was introduced in jQuery 1.4.

If the repetition bothers you, you could make it a plugin:

$.fn.pulsate = function( number, time){
   for(var i = 0; i < number; i++){
      this.fadeIn(time).fadeOut(time);
      if(i != number - 1) this.delay(time);
   }
   return this;
}

It could then be used like this:

$("#notification").pulsate( 3, 500 );
Doug Neiner
Well, I spent all of 3 minutes learning about actual js structure (instead of just relying entirely on jQuery), and I decided to wrap it in a while loop that counts to 3. But, since you gave an equally good solution, you get the credit. Thanks!
Raggedtoad
While I have the attention of a js pro like you, could you also recommend a good way to start with the text in the div having one color, then after the animations are done, it changes to a different color?
Raggedtoad
If you want to animate it, look into the jQuery Color plugin. Otherwise, change your last call to something like this: `.fadeIn(500, function(){ $(this).css('color', 'red') });`
Doug Neiner
+1  A: 

I think it would be better to use it in callback. Create recursive function with limit of fading.

animation(max, total) {
   if (total < max) $(...).animate(..., animation(max, total + 1));
}
dfens