Search code examples
jqueryhtmlcssfadeinfadeout

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!


Solution

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