beenstuckonthiscodeforever beenstuckonthiscodeforever - 3 months ago 21
Javascript Question

traffic light sequence lights won't change

I am trying to create a traffic light simulation using html and JavaScript. I managed to get the starting image to display but the button just doesn't work.

Answer

just take this (you ought to run this with Internet)

<html>
<body>

<p>Click the button to change to the next light.</p>

<img id="starting_light" src="http://mars.wiwi.hu-berlin.de/mediawiki/sk/images/thumb/1/1f/Red_Light_Icon.svg/232px-Red_Light_Icon.svg.png">

<button type="button" onclick="nextLightClick()">Next Light</button>

<script>

var lights = new Array("http://mars.wiwi.hu-berlin.de/mediawiki/sk/images/thumb/1/1f/Red_Light_Icon.svg/232px-Red_Light_Icon.svg.png","https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Yellow_Light_Icon.svg/232px-Yellow_Light_Icon.svg.png","https://upload.wikimedia.org/wikipedia/commons/4/4b/Green_Light_Icon.svg");



var index = 0;
var lightsLen = lights.length;

function nextLightClick() {
    index++;

    if (index == lightsLen) 
        index = 0;

    var image = document.getElementById('starting_light');
    image.src = lights[index];
}
</script>

</body>
</html>