CaribouCode
CaribouCode

Reputation: 14398

jQuery looping .each function

I've got a bunch of blockquotes that I've managed to get to fade in one after another. At the moment, after the last one has faded in and out, the function ends. But I want it to loop and start from the beginning again. Here's my code so far that works:

$("div.quotes blockquote").each(function (index){
  $(this).delay(4500*index).fadeIn(500).delay(4000).fadeOut(500);
});

How do I get it to loop?

Upvotes: 2

Views: 207

Answers (4)

A. Wolff
A. Wolff

Reputation: 74420

Could be done like this, depends what you need exactly: http://jsfiddle.net/MmPgG/

(function loopAnim() {
    var $elems = $("div")
    $elems.each(function(index) {
        var $that = $(this);
        (function() {
            $that.delay(4500 * index).fadeIn(500).delay(4000).fadeOut(500, function() {
                if (index == $elems.length - 1) {
                    $elems.show();
                    loopAnim()
                }
            });

        })($that)
    });
})()​

Upvotes: 0

Francis Kim
Francis Kim

Reputation: 4285

function loop() {
    $("div.quotes blockquote").each(function(index) {
        $(this).delay(4500 * index).fadeIn(500).delay(4000).fadeOut(500, function() {
            loop();
        });
    });
}

loop();​

Upvotes: 0

VisioN
VisioN

Reputation: 145378

One possible solution:

function run() {
    var els = $("div.quotes blockquote");
    els.each(function(i) {
        $(this).delay(4500 * i).fadeIn(500).delay(4000).fadeOut(500, function() {
            if (i == els.length - 1) run();
        });
    });
}
run();

DEMO: http://jsfiddle.net/eDu6W/

Upvotes: 2

svenbravo7
svenbravo7

Reputation: 317

function toggleBlockQuotes()
{
    var countBlockquotes = $("div.quotes blockquote").length;
    var b = 1;
    $("div.quotes blockquote").each(function (index)
    {
        $(this).delay(4500*index).fadeIn(500).delay(4000).fadeOut(500);
        b++;
        if(b == countBlockquotes)
        {
            toggleBlockQuotes();
        }
    });
}

Take note that this will create an infinite loop.

Upvotes: 0

Related Questions