I am trying to list multiple images on a page with the below, whereas when you click the image it opens in modal.
It is working for the first image but no others, I am assuming it's a JS issue, I've tried setting an empty var then setting it to get the element id (which is the same for each img) but again only the first works.
<?php foreach ($img as $thumbnail) {
echo '<img id="myImg" src="'.$thumbnail.'" width="300" height="200">
<div id="imgModal" class="modal">
<span class="closeModal">×</span>
<img class="modal-content" id="myImg1">
<div id="caption"></div>
</div>
<span class="closeModal">×</span>';
}
?>
<script>
var modal = document.getElementById('imgModal');
var img = document.getElementById('myImg');
var modalImg = document.getElementById("myImg1");
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
}
var span = document.getElementsByClassName("closeModal")[0];
span.onclick = function() {
modal.style.display = "none";
}
</script>
Your code includes the same id
attribute for different elements but id
must be unique.
id
attribute specifies a unique identifier for an HTML element so you can manipulate it via JS or CSS. If you are using the same id
for different elements you will only get the first one on the page.
If you want to add event listener to multiple elements add a class
to your <img>
:
echo '<img id="myImg" src="'.$thumbnail.'" width="300" height="200" class="modal-img">
And after that add event listener for every element with a class modal-img
.