Joseph.JJ Joseph.JJ -4 years ago 114
Javascript Question

What does list[nextlight] do in this code?

I've been working on this code for a few weeks and I asked my teacher for help and he added this line

firstlight.src = list[nextlight];
which made it all work. He explained it to me but I just didn;t get the point and how it worked. Can someone explain to me why we equal the source image to list[nextlight]?

my code:

<!DOCTYPE html>

<h1>JavaScript Code</h1>
<p>Traffic Light</p>

<img id="traffic" src="only red1.jpg">
<button type="button" onclick="ChangeLight()">Change Light</button>

var list = ["only red1.jpg","red-yellow 2.jpg", "green3.jpg","yellowonly4.jpg"];
var nextlight = 0;
function ChangeLight() {
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
firstlight.src = list[nextlight];

Answer Source

There is a global variable called nextLight which is equal to 0. Upon the button click the function increments this number so nextLight is 1.

Then it checks if the new number is equal to the length of the list. If it is equal that means that the first image should be selected again.

Why? Because arrays in JavaScipt has a 0-base index which means an array of 4 elements has the length of 4 but the last index 3 since it starts at 0, 1, 2, 3.

It then for each click it changes the src of the image (firstlight.src = list[nextlight]) with each respective url at list[0], list[1], list[2], list[3] and when it reaches index 4 it resets to list[0] again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download