What you want to do is called a carousel or a slider.
There are a lot of examples in many different languages on the web.
Sorry about the confusing title, I don't know what that's called but basically I want an image section that displays 4 images and once and loops through an array of images that when the last one is showed the first one appears again behind it, so the images never end.
This is what I have so far however I can't get the loop to work.
// set index and transition delay
let index = 0;
let transitionDelay = 2000;
let slidesToShow = 4;
// get div containing the slides
let slideContainer = document.querySelector(".slideshow");
// get the slides
let slides = slideContainer.querySelectorAll(".slide");
// set transition delay for slides
for (let slide of slides) {
slide.style.transition = `all ${transitionDelay / 1000}s linear`;
}
// show the first slide
showSlide(index);
// show a specific slide
function showSlide(slideNumber) {
let endSlide =
slideNumber + slidesToShow > slides.length
? slideNumber + slidesToShow - (slides.length - 1)
: slideNumber + slidesToShow;
slides.forEach((slide, i) => {
// slide.style.display = i == slideNumber ? "block" : "none";
if (slideNumber > endSlide && i < endSlide) {
slide.style.display = "block";
} else if (i >= slideNumber && i < endSlide) {
slide.style.display = "block";
} else {
slide.style.display = "none";
}
});
// next index
index++;
// go back to 0 if at the end of slides
if (index >= slides.length) {
index = 0;
}
}
// transition to next slide every x seconds
setInterval(() => showSlide(index), transitionDelay);
I think the problem is in endSlide but I'm not sure. My logic for that part was if I assume the total slides are 10, then if the slideNumber is 8 then the endSlide should be 8+4=12 -> 12-(10-1)=1
How can I fix it so that it loops smoothly? here is the code on a codesandbox so you can see what I mean https://codesandbox.io/p/sandbox/3xnnjt
Please or to participate in this conversation.