Javascript changing between three images at the click of a button

<!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 wrote that part of the code and images change one at a time every time I press a button, but I can’t figure out how to change the order if I keep pressing, that is, traffic lights are red, yellow, green, yellow, etc. every time i click. I am not familiar with jQuery, so I would like not to use them ideally, but if someone can fully explain this with jQuery at work, he will have to do it.

+4
source share
1 answer

The 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>
Run codeHide result
+2
source

Source: https://habr.com/ru/post/1657074/


All Articles