Skip to content
Advertisement

Slide Show using JS array

The image is not get loaded by this code any improvement needed? image url is stored into array for accessing that we required something?

<script>
    var images = ["lap2.png", "lap1.png", "tv1.png", "tv2.png"];
    var i;

    function slides() {
        for (i = 0; i < 4; i++) {
            setInterval(function() {
                document.getElementById('slider').src = "" + images[i];
            }, 8000);
        }

    }
</script>
<!--HTML CODE-->
<p id="slide"><img src="lap1.png" id="slider" onload="this.onload=null; 
this.src=slides();" multiple>
</p>

Advertisement

Answer

 var images = ["1.png", "2.png", "3.png", "4.png"];
 let i=0;
 setInterval(function() {
   i = i < images.length -1 ? i + 1 : 0; 
   document.getElementById('slide').src =  `http://placehold.it/300x150?text=${images[i]}`;
 }, 1000);
<img id="slide" src="http://placehold.it/300x150?text=1.png"></img>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement