I’m trying to make multiple slideshows to work with the same piece of javascript code.
Here is my HTML code:
<div class="slider-container">
<div class="slider">
<div class="slide">...</div>
<div class="slide">...</div>
<div class="slide">...</div>
<div class="slide">...</div>
</div>
<div class="slider">
<div class="slide">...</div>
<div class="slide">...</div>
<div class="slide">...</div>
<div class="slide">...</div>
</div>
</div>
Here is the main CSS:
.slider-container{
width:50%;
}
.slider{
width:100%;
position:relative;
padding-bottom:75%; /* aspect-ratio 4/3 */
}
.slide{
width:100%;
position:absolute;
top:0;
left:0;
opacity:0;
transition:opacity 0.5s ease-in;
}
.slide:first-child{
opacity:1;
}
and here is the javascript :
const sliderContainer = document.querySelector(".slider-container");
const slide = sliderContainer.querySelectorAll(".slide");
let currentSlide = 0;
function changeSlide() {
slide[currentSlide].style.opacity = 0;
currentSlide = (currentSlide + 1) % slide.length;
slide[currentSlide].style.opacity = 1;
}
function startSlider() {
intervalId = setInterval(changeSlide, 2000);
}
function stopSlider() {
clearInterval(intervalId);
}
startSlider();
sliderContainer.addEventListener("mouseenter", stopSlider);
sliderContainer.addEventListener("mouseleave", startSlider);
This javascript works well for one slideshow but II can’t get more than one to work on the same page. Ideally, I would like to keep the same class for all the slideshows and obviously make the enter/leave mouse events work individualy for each of them. Any help ?
2
Answers
To handle multiple sliders on one page with independent behaviors, you need to change your JS code to work with each slider separately.
First way to do this is by encapsulating the functionality for each slider within a function and then creating instances for each slider.
Here is your code:
html:
javascript:
Changes in the code:
createSlider
function takes thesliderId
parameter, who will be used to identify each slider container.document.getElementById
to find the specific slider container based on the providedsliderId
.So, you can create as many sliders as you need by calling
createSlider
with differentsliderId
values. Each slider will have it own set of event listeners and will function independently of the others.Try this: