javascript - Slideshow in modal in a foreach statement
one text
I have a post loop to display a list of custom post types in cards. Each has an image and when you click the image it expands a modal which I am then trying to display a slideshow of all the images for that post so the user can scroll through all of the images.
I am using some JavaScript to create the slideshow in each modal. My code is only working for the first post returned and does not work for the rest.
How can I edit the JavaScript to work separately for each of the posts?
PHP
<div class="modal-body">
<div class="slideshow-container">
<div class="w3-content w3-display-container">
<?php if( $images ): ?>
<?php foreach( $images as $image ): ?>
<div class="mySlides">
<img class="expanded-img" style="width:100%;" src="<?php echo $image['sizes']['large']; ?>" alt="<?php echo $image; ?>">
</div>
<button class="Prev w3-button w3-black w3-display-left" onclick="plusSlides(-1)">❮</button>
<button class="Next w3-button w3-black w3-display-right" onclick="plusSlides(1)">❯</button>
<?php endforeach; ?>
<?php endif;
?>
</div>
</div>
</div>
JavaScript
<script>
let slideIndex = 1;
showSlides(slideIndex);
// Next/previous controls
function plusSlides(n) {
showSlides(slideIndex += n);
}
// Thumbnail image controls
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
let i;
let slides = document.getElementsByClassName("mySlides");
let dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 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";
}
</script>
Source