Search code examples
javascriptloopseachdelay

simple advert changer - each() loop won't delay()


I am trying to create advertisement box which simply changes picture after given time. I used each() loop to hide and display images one after another but all i get is same time effect on all pictures. Any clue how to fix that ?

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title of the document</title>
    <link rel="stylesheet" type="text/css" href="advert.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <style>
        .advert{
            position: relative;
        }
        .advert img{
            position: absolute;
            /*visibility: hidden;*/
        }
    </style>
</head>

<body>
    <div class="advert">
        <img src="img/img1.jpg" alt="Smiley face" height="" width="">
        <img src="img/img2.jpg" alt="Smiley face" height="" width="">
        <img src="img/img3.jpg" alt="Smiley face" height="" width="">
    </div>
</body>

<script>
    $(function(){
        function simpleAdvert(){
            var section = $('.advert');
            var images = section.find('img');
            images.each(function(){
                $( this ).fadeToggle(5000).fadeToggle(5000).delay(10000);
                console.log($( this ));
            });
        }

        simpleAdvert();
    });
</script>

</html>

Solution

  • .each(function) calls the function for each item in the array immediately, which is why the time effect is applied to all items rather than doing what you expect. To get the pictures to show/hide in a loop you need something like a setInterval which calls a function repeatedly. This should work:

    $(function(){
        var timeToShow = 750;
        var timeToFade = 250;
        var timeTotal = timeToShow + timeToFade;
    
        function simpleAdvert(){
            var section = $('.advert');
            var images = section.find('img');
            var index = 0;
            images.hide();
            $(images[0]).show();
            setInterval(function() {
                var next = (index + 1) % images.length;
                $(images[index]).fadeToggle(timeToFade);
                $(images[next]).fadeToggle(timeToFade);
                index = next;
            }, timeTotal);
        }
    
        simpleAdvert();
    });
    

    Essentially this hides all images except the first, then fades out the shown picture and fades in the next picture on an interval.