I have an image modal and I had it on the image from ID which obviously didn't work, so I changed id to class and now the image modal isn't working at all and I can't see what's wrong with it. All and any help is appreciated.
HTML Modal
<div id="myModal" class="modal">
<span class="close">x</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
Image PHP
"<tr><td><img class='myImg' src='" . $fileName . "' alt=' ". $obj->Description . "' width='50px'>" .
Javascript
var modal = document.getElementById("myModal");
var img = document.getElementsByClassName("myImg");
for(var i=0; i<img.length; i++){
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img[i].addEventListener = ('click', function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
})
}
var span = document.getElementsByClassName("close")[0];
document.addEventListener("keydown", function(event) {
const key = event.key;
if (key === "Escape") {
modal.style.display = "none";
}
})
span.onclick = function() {
modal.style.display = "none";
}
The click event listener in the for loop is wrong. You are currently assigning the callback function to the addEventListener method.
img[i].addEventListener = ('click', function(){
This should be:
img[i].addEventListener('click', function() {