How to infinite loop auto 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:
https://codepen.io/viper1/pen/WNzYWNW

Javascript code:

const carousels = document.querySelectorAll(‘.img-carousel’);
const prevBtn = document.querySelectorAll(‘.prev’);
const nextBtn = document.querySelectorAll(‘.next’);
let carsouselImages = document.querySelectorAll(‘.img-carousel div’);

//Next Carousel
carousels.forEach((carousel, index)=>{

const nextCarousel = () => {
if(carsouselImages[carsouselImages.length - 1]) {
carousel.scrollTo(0, 0);
}
carousel.scrollBy(300, 0);
};

nextBtn[index].addEventListener(‘click’, e => {
nextCarousel();
});

//Prev Carousel
const prevCarousel = () => {
if(carsouselImages[0]) {
carousel.scrollTo(4800,0);
}
carousel.scrollBy(-300, 0);
};

prevBtn[index].addEventListener(‘click’, e => {
prevCarousel();
});

// Auto carousel
const auto = true; // Auto scroll
const intervalTime = 5000;
let sliderInterval;

if (auto) {
sliderInterval = setInterval(nextCarousel, intervalTime);
};

carousel.addEventListener(‘mouseover’, (stopInterval) => {
clearInterval(sliderInterval);
});

carousel.addEventListener(‘mouseleave’, (startInterval) => {
if (auto) {
sliderInterval = setInterval(nextCarousel, intervalTime);
}
});

//for mobile events
carousel.addEventListener(‘touchstart’, (stopIntervalT) => {
clearInterval(sliderInterval);
});
carousel.addEventListener(‘touchend’, (startIntervalT) => {
if (auto) {
sliderInterval = setInterval(nextCarousel, intervalTime);
}
});

//Debounce
var previousCall;
window.addEventListener(‘resize’, () => {
if (previousCall >= 0) {
clearTimeout(previousCall);
}

});
});

hello and welcome to fcc forum :slight_smile:

this is a refreshing change of pace for a ‘carousel’ experience for me, i always pictured it as ‘next photo’ kind of scenarios, unlike scrolling into view!! noice!! :grinning:

btw, maybe this example from w3c might be useful!! happy coding :slight_smile: Tryit Editor v3.7

fyi, it moves both ways horizontally!! for that script!!

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