I have made a carousel and my problem is this: I want it to visually seamlessly loop, meaning I want the moment it reverts back to starting position to be unnoticeable by the user. I am posting the JS part only.
<script>
document.addEventListener("DOMContentLoaded", function() {
const carouselTrack = document.querySelector('.carousel-track');
const slides = document.querySelectorAll('.slide');
const totalSlides = slides.length;
const slideWidth = 600; // Width of each slide
const gap = 12; // Gap between slides
const numClones = 2; // Number of clones at each end
let currentIndex = numClones;
// Clone slides for seamless looping
for (let i = 0; i < numClones; i++) {
for (let j = 0; j < totalSlides; j++) {
carouselTrack.appendChild(slides[j].cloneNode(true));
}
}
// Add extra clones at the beginning and end
for (let i = 0; i < numClones; i++) {
const cloneSlideEnd = slides[i].cloneNode(true);
const cloneSlideStart = slides[totalSlides - numClones + i].cloneNode(true);
carouselTrack.appendChild(cloneSlideEnd);
carouselTrack.insertBefore(cloneSlideStart, carouselTrack.firstChild);
}
// Apply transition after a short delay for the initial transition frame
setTimeout(() => {
carouselTrack.style.transition = 'transform 0.5s ease-in-out';
}, 10);
// Automatic sliding
setInterval(() => {
currentIndex++;
if (currentIndex === totalSlides + (2 * numClones) - 1) {
currentIndex = numClones;
carouselTrack.style.transform = `translateX(-${(numClones * (slideWidth + gap))}px)`;
}
carouselTrack.style.transition = 'transform 0.5s ease'; // Re-enable transition for smooth sliding
const translation = (currentIndex * (slideWidth + gap)) - (numClones * (slideWidth + gap));
carouselTrack.style.transform = `translateX(-${translation}px)`;
}, 500); // Adjust speed as needed
});
</script>
I do not know how to further go about this any suggestions very appreciated.
New contributor
Iasonas Galanis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.