Search code examples
jquerydelayinfinite-loop

fade images in an endless loop


I have a single fade from image 1 to image 2 but what I would like is, to fade from image1 to image2 to image3 to image1.. and so on, infinite in a while(true) kind of fashion, endlessly. How can I do this. Waht i have can be seen here: http://jsfiddle.net/bbqunfhu/23/ I have tried to achieve a second fade after a delay(2000) but even this somehow doesn't seem to work. Any assistance would be appreciated.


Solution

  • See http://jsfiddle.net/bbqunfhu/24/

    You can't animate background-image so you need to include different div s with different backgorunds and iterate over them. This is what you can to iterate all divs with a certain class. What this does is; it gets all divs, finds the first visible div, fades it out, on fadeOut's callback, it finds the next div (if the current div is the last div, it gets the first div by use of %) and fades that in. If you need to add more background images just add them to the page with the bckgnd class and you won't need to modify the code.

    $(document).ready(function(){
        setInterval(fadeDivs, 2000); //call it every 2 seconds
    
        function fadeDivs() {
        var visibleDiv = $('.bckgnd:visible:first'); //find first visible div
        visibleDiv.fadeOut(400, function () {  //fade out first visible div
           var allDivs = visibleDiv.parent().children(); //all divs to fade out / in
           var nextDivIndex = (allDivs.index(visibleDiv) + 1) % allDivs.length;  //index of next div that comes after visible div
           var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
           nextdiv.fadeIn(400); //fade it in
        });
        };
    
    });