Walrus
Walrus

Reputation: 20444

JQuery Infinite Loop for function

Here is a simple JQuery ticker I have written. How would I make it continue to tick after it gets to the end. At the moment it stops at the end of the sequence.

$('#fader').children().hide();

$.fn.seqfx = function() {

    $(this).fadeIn(400);
    $(this).delay(4000);
    $(this).fadeOut(300, function() {
        $(this).next().seqfx();

}); 
 };

$(document).ready(function()
{
    $("#fader div:first").seqfx();
});

I tried if ($(this).is('div:last')) { $(this).first().seqfx(); }; else $(this).next().seqfx();

but it just repeats the first element constantly.

Any ideas?

Marvellous

Upvotes: 2

Views: 9804

Answers (2)

Felix Kling
Felix Kling

Reputation: 816334

I think a better approach is to select all elements the trigger should rotate and then loop over the selected elements:

(function($) {
    $.fn.seqfx = function() {
        var elements = this,
            l = elements.length,
            i = 0;

        function execute() {
            var current = $(elements[i]);
            i = (i + 1) % l;

            current
               .fadeIn(400)
               .delay(4000)
               .fadeOut(300, execute);
        }
        execute();
        return this;
    } ;
}(jQuery));

And then call it with

$("#fader div").seqfx();

Here is a DEMO

Upvotes: 5

Naftali
Naftali

Reputation: 146302

try this instead:

$(document).ready(function()
{
    setInterval(function(){
      $("#fader div:first").seqfx();
    },4800);
});

Upvotes: 2

Related Questions