Raggedtoad
Raggedtoad

Reputation: 521

jQuery: fade div in and out multiple times

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.

Upvotes: 2

Views: 3797

Answers (2)

dfens
dfens

Reputation: 5515

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));
}

Upvotes: 1

Doug Neiner
Doug Neiner

Reputation: 66191

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 );

Upvotes: 8

Related Questions