How to make prev/next buttons for multiple js slideshow?

Viewed 70

How could I make the slides clickable to navigate forward in the slider? That is how could I make the plusSlides function work for each individual slideshow on one page?

This is the main structure of any slideshow which I could repeat in the same page.

HTLM

<div class="slideshow-container" data-cycle="2000">
    <div class="slider fade"><img onclick="plusSlides()" src="assets/img/1.jpg"></div>
    <div class="slider fade"><img onclick="plusSlides()" src="assets/img/2.jpg"></div>
    <div class="slider fade"><img onclick="plusSlides()" src="assets/img/3.jpg"></div>
    <div class="slider fade"><img onclick="plusSlides()" src="assets/img/4.jpg"></div>
    <div>
        <span class="dot"></span> 
        <span class="dot"></span> 
        <span class="dot"></span>
        <span class="dot"></span>
    </div>
</div>

And this code which works for any slider with the same structure and contained in a div with the class slideshow-container. The slideshows are automatic and have dots.

JS


var slideshowContainers = document.getElementsByClassName("slideshow-container");
for(let s = 0; s < slideshowContainers.length; s++) {
    var cont = slideshowContainers[s];
    var cycle = slideshowContainers[s].dataset.cycle;
    var slides = slideshowContainers[s].querySelectorAll('.slider');
    var dots = slideshowContainers[s].querySelectorAll('.dot');
    var slideIndex = 0;
    showSlides(cont, slides, slideIndex, cycle, dots);
};
            
var timer = null;

function showSlides(cont, slides, slideIndex, cycle, dots) {
    var cont;
    slideIndex++;
    if (slideIndex > slides.length) {
        slideIndex = 1
    }
    if (slideIndex < 1) {
        slideIndex = slides.length
    }         
    for (cont = 0; cont < slides.length; cont++) {
        slides[cont].style.display = "none";
    }
    for (cont = 0; cont < dots.length; cont++) {
         dots[cont].className = dots[cont].className.replace(" active", "");
    }
    slides[slideIndex-1].style.display = "block";
    dots[slideIndex-1].className += " active";

    setTimeout(function() {
        showSlides(cont, slides, slideIndex, cycle, dots)
    }, cycle);
};
0 Answers
Related