Reputation: 73
I am currently working on a website and have just created an image carousel using CSS, HTML and JavaScript. I was wandering how I could get the carousel to change slide automatically every 3 seconds for example. What could I add to my code to achieve that? Here is my code.'
HTML:
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>
</div>
JavaScript:
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)';
nextBtn.addEventListener('click', () => {
if (counter >= carouselImages.length - 1) return;
carouselSlide.style.transition = "transform 0.4s ease-in-out";
counter++;
carouselSlide.style.transform = 'translateX(' + (-carouselImages[0].clientWidth * counter) + 'px)';
});
prevBtn.addEventListener('click', () => {
if (counter <= 0) return;
carouselSlide.style.transition = "transform 0.4s ease-in-out";
counter--;
carouselSlide.style.transform = 'translateX(' + (-carouselImages[0].clientWidth * counter) + 'px)';
});
carouselSlide.addEventListener('transitionend', () => {
console.log(carouselImages[counter]);
if (carouselImages[counter].id === 'lastClone') {
carouselSlide.style.transition = "none";
counter = carouselImages.length - 2;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
if (carouselImages[counter].id === 'firstClone') {
carouselSlide.style.transition = "none";
counter = carouselImages.length - counter;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
});
Thank you in advance!
Upvotes: 0
Views: 396
Reputation: 1003
This should work. If not please provide a working snippet for validation.
var interval = 3000; // 1000 = 1 sec
setInterval(function(){
var offset = counter%(carouselImages.length);
carouselSlide.style.transition = "transform 0.4s ease-in-out";
carouselSlide.style.transform = 'translateX(' + (-carouselImages[0].clientWidth * offset) + 'px)';
counter++;
if(offset == 0) counter = 1; // to reset counter so next and prev button should work
}, interval);
Upvotes: 1