Ben Parkes Ben Parkes - 5 months ago 41
HTML Question

Could you help me Explain what this means?

Hello again guys i have recently found this code on another forum that i made the only problem that i am having is trying to explain what the code actually means

var list=["Red.jpg","Amber.jpg","Green.jpg","AmberLast.jpg"];
var index = 0;

function changeLights() {
var image = document.getElementById('Red.jpg');
var display = document.getElementById('display');
index = (index + 1) % 4;
image.src = list[index];
display.innerHTML = list[index]


Thanks For your help guys i hope i can hear your answers soon

<!DOCTYPE html>
<html>
<body>
<h1>Traffic Light Sequence</h1>

<img id="Red.jpg" src="Red.jpg">

<button type="button" onclick="changeLights()">Change Lights</button>

<script>
var list=["Red.jpg","Amber.jpg","Green.jpg","AmberLast.jpg"];
var index = 0;

function changeLights() {
var image = document.getElementById('Red.jpg');
var display = document.getElementById('display');
index = (index + 1) % 4;
image.src = list[index];
display.innerHTML = list[index];

}
</script>

</body>
</html>


Here is my entire code

Answer
var list=["Red.jpg","Amber.jpg","Green.jpg","AmberLast.jpg"];

this is an array of names of image sources.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

  var index = 0;

this a variable, it's called index, and has the value of 0 because you can target an element of an array (e.g Amber.jpg) using it's index. An array's index by default starts at 0 (zero based), so in the 'list' array above, the index of 0 (list[0]) will return 'Red.jpg'.

  function changeLights() {

    var image = document.getElementById('Red.jpg');
    var display = document.getElementById('display');
    index = (index + 1) % 4;
    image.src = list[index];
    display.innerHTML = list[index];

  }

This function selects the <img> tag with the ID of 'Red.jpg', and then sets it's src= to be index + 1 (= 1), and then sets the inner HTML of the element with an ID of display to be Amber.jpg (list[1]).

The correct way to 'change lights' would instead be:

var list=["Red.jpg","Amber.jpg","Green.jpg","AmberLast.jpg"];

var index = 0;

function changeLights() {

   var max = list.length - 1;
   var next = index += 1; 

   if(next > max) {
      next = 0; //start back at beginning
      index = 0;
   }  

   var image = document.getElementById('IDOFIMAGETAG'); //replace will correct ID of <img>

   image.src = list[next];

}
Comments