Julian Abal
Julian Abal

Reputation: 49

jQuery automatically fade in next html element then loop to restart

I have:

<a id="item<?php echo $i; ?>">...</a>
<a id="item<?php echo $i; ?>">...</a>
...

Where $i will be the value of the current iteration starting from 1 and will render something like:

<a id="item1">...</a>
<a id="item2">...</a>
...

What I need is a script to keep visible only the first element, then after a few seconds (lets say 4-5) fade out and fade in the next one. And repeat this cycle until last element. Then loop to start it all over again.

No "pause" or next/prev elements needed.

Thank you in advance!

Upvotes: 0

Views: 1411

Answers (2)

andi
andi

Reputation: 6522

You can use this JS: ( http://jsfiddle.net/KWmgf/ )

var fadeLoop = function($el) {
    $el.fadeOut(4000, function() {
        var $next = $el.next();
        if ($next.length == 0) {
            $next = $el.siblings(":first");
        }
        $next.fadeIn(4000, function() {
            fadeLoop($next);
        });
    });
};

$(document).ready(function(){
    $("#item1").siblings().hide();
    fadeLoop($("#item1"));
});

Upvotes: 2

Michael Malinovskij
Michael Malinovskij

Reputation: 1422

Set all a (or better add some CLASS attribute to them) elements style to display:none axcept the first one.

And add script:

setInterval(function() {
var $visible = $('.CLASS:visible');
$visible.hide();

if ( $visible.is(':last') ){
   $visible.siblings(':first').show()
} else {
   $visible.next().show();
}
}, 3000);

replace CLASS with real a class name

Upvotes: 0

Related Questions