I have a div that contains 4 divs. There is an autoSlide() function that makes the slides move forward every 3s, a next and a prev button.
Everything works fine, but when I click the prev button I want the auto slide to stop, go back to the previous slide and restart the auto slide again.
I managed to stop the timer but I don’t know how to restart the auto slide.
HTML:
<div class="slides-wrapper">
<div class="slide">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
<div class="slide">4</div>
</div>
<button class="prev">Prev</button>
<button class="next">Next</button>
CSS:
.slides-wrapper {
position: relative;
height: 100vh;
}
.slide {
position: absolute;
border: 1px solid black;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 5rem;
}
.prev {
position: fixed;
top: 50%;
}
.next {
position: fixed;
top: 50%;
right: 5px;
z-index: 10;
}
JS:
const prevButton = document.querySelector('.prev');
const nextButton = document.querySelector('.next');
const slides = document.querySelectorAll('.slide');
slides.forEach((slide, index) => {
slide.style.transform = `translateX(${index * 100}%)`;
});
let currentSlide = 0;
let maxSlide = slides.length - 1;
let timer;
function autoSlide() {
if(currentSlide === maxSlide) {
currentSlide = 0;
} else {
currentSlide++;
}
// Move slides to the left //
slides.forEach((slide, index) => {
slide.style.transform = `translateX(${100 * (index - currentSlide)}%)`;
});
timer = setTimeout(autoSlide, 3000);
}
nextButton.addEventListener('click', () => {
// Reset timeout //
if (timer) {
clearTimeout(timer);
}
autoSlide();
})
prevButton.addEventListener('click', () => {
if (timer) {
clearTimeout(timer);
}
if(currentSlide == 0) {
currentSlide = maxSlide;
} else {
currentSlide--;
}
// Move slides to the right //
slides.forEach((slide, index) => {
slide.style.transform = `translateX(${100 * (index - currentSlide)}%)`;
});
})
autoSlide();