0

I just was wondering what a code that could loop an array of images may look like. I have an example but cannot see why it does not work:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" language="JavaScript">
    var i =0;
    var trafficarray=["1.gif","2.gif","3.gif","4.gif"];
    var image = document.getElementById("trafficlights");

    function cycle(){
      i+=1;
      document.getElementById("trafficlights").src=trafficarray[i];
      if (i>2) {i=-1};
    }
  </script>
</head>

<body>
  <img src="1.gif" id="trafficlights">
  <button onClick="setInterval(cycle,1000)">click me</button>
</body>

Michelangelo
  • 5,888
  • 5
  • 31
  • 50
K.Dawn
  • 1
  • 1

2 Answers2

2

Your code does work. Perhaps you mean that the images are not loading. In this case, make sure "1.gif" and the rest of the files exist in the same directory that your webpage is served on, otherwise you may see broken links.

Steve B
  • 212
  • 1
  • 8
0

Never mind all! I have fixed it:

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" language="JavaScript">
var i =0;
var trafficarray=["1.gif","2.gif","3.gif","4.gif"];
var image = document.getElementById("trafficlights");

function cycle()
{
i+=1;
document.getElementById("trafficlights").src=trafficarray[i]
if (i>2) {i=-1};
}
</script>
</head>

<body>

<img src="1.gif" id="trafficlights">
<button onClick="setInterval(cycle,1000)">click me</button>
</body>
</html>

Or alternatively:

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" language="JavaScript">
var i =0;
var trafficarray=["1.gif","2.gif","3.gif","4.gif"];
var image = document.getElementById("trafficlights");

function cycle()
{
i+=1;
document.getElementById("trafficlights").src=trafficarray[i]
if (i>2) {i=-1};
}
</script>
</head>

<body>

<img src="1.gif" id="trafficlights">
<button onClick="cycle()">click me</button>
</body>
</html>
K.Dawn
  • 1
  • 1
  • 1
    I'm not sure I get it. What did you fix? Your first code is the same thing you posted in your question. And the second code just makes it change on click instead of on a timer. – villecoder Feb 10 '16 at 19:20