How to infinite loop automatic carousel

I have an auto slide carousels which are not infinite loop. The problem is when a carousel reach the last image it stops and don’t slide back to the first image. I need the carousels to be infinite loop but I can’t make it myself. Can somebody help?

Here it is in codepen:

We can get the current left position of the scroll window with carousel.scrollLeft
We can also get the total width of the scroll window with carousel.scrollWidth

To check if we are at the end of the scroll, we need more than just carousel.scrollLeft. We also need the width of the image, which is given by carousel.offsetWidth

We can now check if the scroll position plus the image width is less than the full width. If it’s less then we scroll. If it’s not, well then we must already be at the far right, so we scroll back to the start.

      if (carousel.scrollLeft + carousel.offsetWidth < carousel.scrollWidth) {
        carousel.scrollBy(300, 0);
      } else {
        carousel.scrollTo(0, 0);

It’s a similar logic for scrolling left too.

1 Like

While Paul is correct, OP should beware that the number 4800 is incorrect here. It should be the scrollwidth - offsetWidth (4000 in the current scenario; but that number will change depending on the number of images/width of images/etc). A static number to scrollTo (when trying to go left to the end) only works if you’re hardcoding the number of images and their widths.


Thank you. I still wonder why :

if(carsouselImages[carsouselImages.length - 1]) {
  carousel.scrollTo(0, 0); 
  carousel.scrollBy(300, 0);


doesn’t work anymore.? it was working just a few months ago on my laptop and mobile. And also now still working on my old android 9 mobile. Not working anymore on android 11 mobile. Also not working on laptop anymore. whats wrong with that code. bang my head all day.

Well that condition is only checking if there is a last item in the array, which will always be true when there are any items in the array.

Unless you can find the previous code that was working a few months ago, it becomes a matter of guesswork. Find that previous code though, and we can then investigate that and give clear answers.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.