I want to use multiple slideshows on one page. My javascript code is at the moment only designed for one slideshow. How can I adapt this code to work for multiple slideshows that all have the same class names?
I had already been told that I should try javascript classes and constructor, but I hadn't dared to do it yet. I would like to understand how to make the code react slideshow specific rather than global.
document.addEventListener('DOMContentLoaded', () => {
const slideshows = document.getElementsByClassName('slideshow');
for (const slideshow of slideshows) {
slideshow.firstElementChild.className = 'slides showing ';
}
let currentSlide = 0;
const slides = document.getElementsByClassName('slides');
for (const slide of slides) {
slide.addEventListener('click', (event) => {
event.preventDefault();
slides[currentSlide].className = 'slides ';
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].className = 'slides showing';
});
}
});
<!-- kirby cms snippet -->
<?php foreach($data->children()->listed() as $slideshow): ?>
<section id="<?= $slideshow->id() ?>" class="slideshow">
<?php foreach($slideshow->images() as $image): ?>
<div class="slides">
<img src=" <?= $image->resize(null, 500)->url(); ?>" alt="<?=$image->name()?>"
data-slide="{<?= $image->resize(null, 180)->url(); ?>}" />
</div>
<?php endforeach ?>
</section>
<?php endforeach ?>
For someone interested in the solution.