MATTHEW PARKER MATTHEW PARKER - 2 months ago 12
HTML Question

javascript changing between three images on a button click

<!DOCTYPE html>
<html>
<head>
<script>
var trafficlights = ['redlight.png','yellowlight.png','greenlight.png'];
var num = 1

function lightsequence() {
document.getElementById('light').src = trafficlights[num];
num = num + 1;
}
</script>
</head>
<body>
<img id="light" src="redlight.png">
<button onclick="lightsequence()">Change Lights</button>
</body>
</html>


I have written that piece of code and the images change in order one by one each time I click the button but I cannot think of how to reverse the order if I keep clicking, i.e. traffic lights red yellow green yellow red etc. each time I click. I am unfamiliar with jQuery so would like to not use them ideally but if someone can explain it fully with jQuery in working it will have to do.

Answer

Modulo operator is very convenient in such cases:

document.getElementById('light').src = trafficlights[num++ % trafficlights.length];

Here is a demo:

var trafficlights = [
	'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png', 
	'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Yellow.png', 
	'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Green.png'
];
var num = 1

function lightsequence() {
  document.getElementById('light').src = trafficlights[num++ % trafficlights.length];
}
<img id="light" src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/48x48/Circle_Red.png">
<button onclick="lightsequence()">Change Lights</button>