Ben Parkes Ben Parkes - 6 months ago 26
Javascript Question

My HTML Button is not running in Javascript

Ok So i'm doing my GCSE Coursework and I've came across a problem with my script

The problem is my button for the script will not work with JavaScript

Here's the script;

</head>
<h1>Traffic Light Sequence</h1>

<img id="Red.jpg" src="Red.jpg">

<button type="button" onclick="changeLights()">Change Lights</button>

<script>
var list=["Red.jpg","Amber.jpg","Green.jpg","Amber.jpg"]

var count:0,1

function changeLights() {
var image = document.getElementById('Red.jpg');
if list=0 {
image.src=list[0];
if list=1 {
image.src=list[1];
} else if list=2 {
image.src=list[2];
} else > 3 {
image.src=list[3];
}

}

</script>

</body>
</html>


I have clearly made the button, created an onClick, and opened a function with it

Answer

Take a look at this code (https://jsfiddle.net/6d3tkm6y/):

<h1>Traffic Light Sequence</h1>

<img id="Red.jpg" src="Red.jpg">

<h2 id="display">Red</h2>

<button type="button" onclick="changeLights()">Change Lights</button>

<script>
  var list=["Red.jpg","Amber.jpg","Green.jpg","Amber.jpg"];
  var index = 0;

  function changeLights() {
    var image = document.getElementById('Red.jpg');
    var display = document.getElementById('display');
    index = (index + 1) % 4;
    image.src = list[index];
    display.innerHTML = list[index];

  }
</script>

The display element in my code is only there so you can see what is happening with the light, since I don't have the image files you're using.

You don't need any of the if..else if statements. You can just use an index to loop over your array. The % 4 automatically wraps your index around once it hits four (So you just need to increase it by one). This way your function is essentially reduced to just 3 lines.

Also, you should definitely look a bit more into some general javascript syntax ;)