I am currently working on an image carousel and I have ran into a problem. The automatic function of my slider does not work as I want it to. When the slider reaches the last image, it goes all the way back to the first image revealing the images between instead of looping back to the first. What can I add to my code to achieve that? Here is the relevant code.
HTML:
<div class="carousel-container">
<i class="fa fa-angle-left" id="prevBtn"></i>
<i class="fa fa-angle-right" id="nextBtn"></i>
<div class="carousel-slide">
<img src="./img/testpic3.jpg" id="lastClone" alt="">
<img src="./img/testpic1.jpg" alt="">
<img src="./img/testpic2.jpg" alt="">
<img src="./img/testpic3.jpg" alt="">
<img src="./img/testpic1.jpg" id="firstClone" alt="">
</div>
</div>
JavaScript:
const carouselSlide = document.querySelector('.carousel-slide');
const carouselImages = document.querySelectorAll('.carousel-slide img');
const prevBtn = document.querySelector('#prevBtn');
const nextBtn = document.querySelector('#nextBtn');
let counter = 1;
const size = carouselImages[0].clientWidth;
carouselSlide.style.transform = 'translateX(' + (-carouselImages[0].clientWidth * counter) + 'px)';
var interval = 3000; // 1000 = 1 sec
setInterval(function() {
var offset = counter % (carouselImages.length - 2);
carouselImages[counter].id === 'firstClone';
carouselSlide.style.transition = "transform 0.4s ease-in-out";
carouselSlide.style.transform = 'translateX(' + (-carouselImages[0].clientWidth * counter) + 'px)';
counter++;
if (offset == 0) counter = 1; // to reset counter so next and prev button should work
}, interval);
Thanks in advance!