I got an automatic slideshow that works manually too. My problem is that I want the timer (for the automatic slideshow) to reset when you press one of the 2 buttons for the manual slideshow. Because now the timer does not reset and the pictures sometimes switch immediately after you just pressed the manual button. Would appreciate any help or input to this problem. Thanks!
var slideIndex = 0;
showSlides();
var slides, dots;
//For the manual slideshow buttons.
function plusSlides(position) {
slideIndex += position;
if (slideIndex > slides.length) {
slideIndex = 1;
} else if (slideIndex < 1) {
slideIndex = slides.length;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
}
//OnClick function for the dots below the slideshow.
function currentSlide(index) {
if (index > slides.length) {
index = 1;
} else if (index < 1) {
index = slides.length;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[index - 1].style.display = "block";
dots[index - 1].className += " active";
}
//Function for the automatic slideshow
function showSlides() {
var i;
slides = document.getElementsByClassName("hero-slides");
dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
/* dots[slideIndex - 1].className += " active"; */
setTimeout(showSlides, 5000);
}
You need to keep the setTimeout handler and reset it, when calling plusSlides() or currentSlide().
So, at the beginning of the file, you should make variable that will be accesible in every function:
var slides, dots, timerHandler;
var autoSlideTimeout = 5000; //(Keeping timeout as variable is also a good idea)
When you call automatic slide, save the handler:
function showSlides() {
//...
timerHandler = setTimeout(showSlides, autoSlideTimeout);
}
And in the two other functions you need to reset the timer:
function plusSlides(position) {
//...
clearTimeout(timerHandler)
timerHandler = setTimeout(showSlides, autoSlideTimeout);
}
function currentSlide(index) {
//...
clearTimeout(timerHandler)
timerHandler = setTimeout(showSlides, autoSlideTimeout);
}