-2
<html>
<body>


<button onclick="ChangeLights()">Change Lights</button>

<img src="redlight.jpg" id="traffic" width="83" height="232">

<script>
    var imgarray = ["redlight.jpg", "yellowlight.jpg", "greenlight.jpg"];
    document.getElementById("traffic").innerHTML = traffic;
    function ChangeLights(){
        document.getElementById("traffic").src = "redlight.jpg";
    }

    function ChangeLights() {
        if (traffic.src.match(imgarray[0])){
            traffic.src = imgarray[1];
        }else if (traffic.src.match(imgarray[1])){
            traffic.src = imgarray[2];
        }else if (traffic.src.match(imgarray[2])){
            traffic.src = imgarray[3];
        }
    }
</script>
</body>
</html>

Whenever I press the button, the image does not appear.

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
Zein
  • 1
  • 1
  • What is `traffic`? You never defined it. You also defined your `ChangeLights` function twice which looks confusing. – putvande Dec 28 '16 at 22:37
  • What exactly do you want to achieve? You need a function which will change image according to clicked button or you want function to change images in a loop? – kind user Dec 28 '16 at 22:37
  • It works fine when I test it. I can't reproduce the problem. – Quentin Dec 28 '16 at 22:39
  • 1
    @putvande — `traffic` is defined via http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables – Quentin Dec 28 '16 at 22:40
  • I want when I click the button for the image to change into the next image, this is all amazing feedback! How I should best achieve that, I'm not sure. – Zein Dec 28 '16 at 22:40
  • @Quentin, ow yes.. missed that. Thanks – putvande Dec 28 '16 at 22:44
  • 1
    @Zein `html`, `javascript` at Question returns expected result described at OP, save for fourth click forwards http://plnkr.co/edit/GfV1fVIWlWi30cOAdRNx?p=preview – guest271314 Dec 28 '16 at 22:47
  • why are you using a regexp? And there is no 4th index... `document.getElementById("traffic").innerHTML = traffic;` makes no sense – epascarello Dec 28 '16 at 22:51

1 Answers1

-1

Try this

<html>

<body>
<button onclick="ChangeLights()">Change Lights</button>
<img src="redlight.jpg" id="traffic" width="83" height="232">
<script>
    var imgarray = ["redlight.jpg", "yellowlight.jpg", "greenlight.jpg"];

    function ChangeLights() {
        if (traffic.src.match(imgarray[0])) {
            traffic.src = imgarray[1];
        } else if (traffic.src.match(imgarray[1])) {
            traffic.src = imgarray[2];
        } else if (traffic.src.match(imgarray[2])) {
            traffic.src = imgarray[0];
        }
    }
</script>

Make sure the images are in the right folder, it should be in the same directory as your HTML file.

YoongTi
  • 27
  • 1
  • 5