I'm working on creating an infinite slider that loops continuously without the need for navigation buttons. Instead, I plan to allow users to control the slider using touch gestures (although this functionality is not yet implemented in the code snippet).
However, I've encountered a problem with the logic of the infinite slider. It seems to start at the last slide (numbered 5 in my case), then goes to slides 2, 3, 4, 5, and finally 1 before stopping. Additionally, I can't figure out why it's disregarding the condition checking the value of currentSlide
.
const allSlides = document.querySelectorAll(".testimonials-tp__review-slider__slide");
const numOfSlides = allSlides.length ;
let currentSlide = 0;
const slider = () => {
// Setting each slide's initial position:
// setToInitialPosition();
// Moving to the next slide after 2s:
setInterval(sliding, 2000);
}
const sliding = () => {
// Reset to the first slide for an infinite loop:
if(currentSlide === 0 || currentSlide === numOfSlides) setToInitialPosition();
// Making the current slide outside the container:
allSlides[currentSlide].style.transform = `translateX(${(currentSlide) * -100}%)`;
// Bring the next slide to the container:
allSlides[currentSlide + 1].style.transform = `translateX(0%)`;
++currentSlide;
}
const setToInitialPosition = () => {
allSlides.forEach((slide, index) => {
// Reset all slides to their initial positions:
slide.style.transform = `translateX(${index * 100}%)`;
});
// Reset the current slide index:
currentSlide = 0;
};
slider();
You can access the complete code here: https://codepen.io/Marya-ai/pen/ZEwRNRE
Your help and suggestions would be greatly appreciated.