-2

I want to fix the button so that the user can click on it in order to start the traffic light slideshow. At the moment, it is interfering with the loop which means that when the user clicks on the button it will fasten the slideshow rather than start it.

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "traffic light_1.png"
var image2 = new Image()
image2.src = "traffic light_2.png"
var image3 = new Image()
image3.src = "traffic light_3.png"
var image4 = new Image()
image4.src = "traffic light_2.png"
</script>
</head>
<body>
<p><img src="traffic light_1.png" width="800" height="500" name="slide" /></p>

<button onclick="slideit()">Click me</button>

<p id="demo"></p>

<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<4)
                step++;
            else
                step=1;
            setTimeout("slideit()",4000);
        }
        slideit();
</script>
</body>
Jack
  • 21

1 Answers1

0

With

var img = new Image()
img.src = ...

you are creating <img src="..." > Image()

Suppose you want to replace thesrc. Therefore one can set an array with the URLs :

var urls = ["img2.jpg", ..., "img1.jpg"];

Give the setted <img> an id and access it with document.getElementById("slide");

Then you have something like this :

var urls = ["http://unsplash.it/300/150?image=2", "http://unsplash.it/300/150?image=3", "http://unsplash.it/300/150?image=4",
"http://unsplash.it/300/150?image=1"];

var step = 0;

function slideit() {
    var s = document.getElementById("slide");
    s.src = urls[step];
    if(step < 3) {
     step++;
    } else {
     step = 0;
    }
}

slideit();
<p>
    <img id="slide" src="http://unsplash.it/300/150?image=1" width="300" height="200" name="slide" />
</p>

<button onclick="slideit()">Click me</button>
  • var urls = ["traffic light_1.png", "traffic light_2.png", "traffic light_3.png", "traffic light_4.png"]; var step = 0; function slideit() { var s = document.getElementById("slide"); s.src = urls[step]; if(step < 4) { step++; } else { step = 0; } }

    – Jack Jun 19 '16 at 21:04
  • The urls are from my files and not from the web. Does this make a difference? – Jack Jun 21 '16 at 21:40
  • I've updated my answer. `var urls = [second img, third img, ..., first img]` and in the HTML ``. I hope this is clear. –  Jun 21 '16 at 21:59
  • What should happen, if you click the button ? Should it slide to the next image **or** should it only **start** a automatically slideshow ? –  Jun 21 '16 at 22:09