Solo
Solo

Reputation: 726

JavaScript Slideshow Not Working

I am programming a very simple JavaScript slideshow and it isn't working. I do not want jQuery. This code displays the first image after 5 seconds, however does not cycle through the rest of the images. The full code is as follows, I just can't figure out what I am doing wrong:

<!DOCTYPE html>
<html dir="ltr" lang="en">
    <head>
        <title>JavaScript Slideshow</title>
        <style>
        #slider > img { display: none }
        </style>
    </head>
    <body>
        <div id="slider">
            <img src="img1.png">
            <img src="img2.png">
            <img src="img3.png">
            <img src="img4.png">
            <img src="img5.png">
        </div>
        <script>
            var s = document.getElementById("slider").getElementsByTagName("img");
            var c = s.length;
            setInterval(function() {
                s[(s.length++) % c].style.display="block";
            }, 5000);
        </script>
    </body>
</html>

Upvotes: 1

Views: 1068

Answers (1)

onon15
onon15

Reputation: 3630

Your code has several errors in it.

  1. You're trying to increment the array length, and modulo it by the counter. I bet you wanted to do that the other way around:

    s[c % (s.length)].style.display="";

  2. You're not hiding the images already cycled through, so your cycle will only display once.

        var s = document.getElementById("slider").getElementsByTagName("img");
        var c = s.length;
        setInterval(function() {
            s[c % s.length].style.display="";
            s[(++c) % s.length].style.display="block";
        }, 5000);
    

Upvotes: 2

Related Questions