Stavia81 Stavia81 - 5 months ago 15
Javascript Question

Can someone halp me out in JavaScript?

I am doing my work in JavaScript and I need to create a traffic light that will change colour every time the button is clicked. I spent a long time on it and I still cannot get it working. Can someone please have a look for me and give me some tips on how to get it work as I am really stuck on it. Thanks very much.

<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Light1.gif" width="500" height ="350">
<p>
<button onclick="myFunction()">Change Light</button>
<p>
<p>Click Change Light to change the traffic light.</p>
<script>
var image = document.getElementById('myImage');
var p1 = new Image();
p1.src = "Light1.gif";

var p2= new Image();
p2.src = "Light2.gif";

var p3 = new Image();
p3.src = "Light3.gif";

var p4 = new Image();
p4.src = "Light4.gif";

var imgArray = [p1,p2,p3,p4];
var n = 0;

function myFunction(){
n = n + 1;
if (n === imgArray.length) {
n = 0
}
image.src = imgArray[n];
}
</script>
</body>
</html>

Answer

First thing, there are syntax errors in your code which you need to check before posting. line terminator ; is missing on most of the lines, and there's an extra brace.

For the problem, you are creating objects of type Image and then mapping it as source to the original image element which will not work. You can just create array of text values (image names), as mentioned below.

<!DOCTYPE html>
<html>

<body>
  <img id="myImage" src="Light1.gif" width="500" height="350">
  <p>
    <button onclick="myFunction()">Change Light</button>
    <p>
      <p>Click Change Light to change the traffic light.</p>
      <script>
        var image = document.getElementById('myImage');
        var p1 = "Light1.gif";
        var p2 = "Light2.gif";
        var p3 = "Light3.gif";
        var p4 = "Light4.gif";
        var imgArray = [p1, p2, p3, p4];
        var n = 0;

        function myFunction() {
          n = n + 1;
          if (n == imgArray.length) {
            n = 0
          };
          image.src = imgArray[n];
        }
      </script>
</body>

</html>

Pro Tip: indent your code for better readability

Comments