0

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.

  • i thought it didnt matter what it was called because it is a function name – beenstuckonthiscodeforever Aug 22 '16 at 12:50
  • Sorry, I edited my previous comment before I saw your reply, but I wasn't commenting on the name of the function, I was indirectly pointing out what the answer below is saying. – nnnnnn Aug 22 '16 at 12:52
  • Valid values for the id attribute in HTML doesn't contain space inside two word. See This link http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html for details. – Biswajit Panday Aug 22 '16 at 12:53

3 Answers3

2

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>
0

You cannot use starting light as an id, you can read more here as pointed in the comments Valid Naming for ID.

Also change index= to index++

You also seem to have a typo, as well as a missing curly braces in the nextLightClick() function. Let me know if this helps!

P.S make sure all the pictures are named properly and in the same directory!

Community
  • 1
  • 1
Muntasir Alam
  • 1,777
  • 2
  • 17
  • 26
0
  1. Use '_' or '-' instead of space in id (starting-light).
  2. If all the images are in the ./ict traffic lights/ folder, then change the image names in the array to be like "./ict traffic lights/red.jpg", "./ict traffic lights/redamber.jpg" etc.
  3. Remove extra brace after index = index ++; line cause otherwise if (index == lightsLen)... part of the code remains outside of the nextLightClick() function.