Skip to content
Advertisement

issue: image carousel skips 1st image

I have an automatic image carousel in javascript for my html website. The carousel has 5 images. The carousel works well on the first round, but on the second round of images, the 1st image doesn’t appear. I’m not sure why? Please help if you can

<script>
            (function(){    
                    var imgLen = document.getElementById('gallery');
                    var images = imgLen.getElementsByTagName('img');
                    var counter = 1; 

                    if(counter <= images.length){
                        setInterval(function(){    
                            images[0].src = images[counter].src;
                            console.log(images[counter].src);
                            counter++;

                            if(counter === images.length){
                                counter = 1;
                            }
                        },5000);   
                    }
            })();
 </script>

Advertisement

Answer

It works the first time because your first image, which I’m assuming is the displayed image, starts with the correct source.

It appears that you are overwriting the source of this image with the other sources. After the first round, the original source of the first image is lost.

At the moment, your image sources are probably something like:

1,2,3,4,5
2,2,3,4,5
3,2,3,4,5
4,2,3,4,5
5,2,3,4,5

for the first round, which is alright. Once the second round starts however, and for subsequent rounds, it would go something like this:

2,2,3,4,5
3,2,3,4,5
4,2,3,4,5
5,2,3,4,5

The simplest solution would be to store the first image as a 6th image, which would work with your existing code.

An alternative solution would be to store image sources in a JavaScript variable and use those as sources instead of referencing other elements.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement