I'm trying to implement some modal images and am having some trouble making a forEach work on an array of elements.
This is my variables declaration:
// Get the modal
var modal = document.getElementsByClassName("modal")[0]
// Get the modal trigger image and the modal content image
var img = document.getElementsByClassName("img-to-modal")
var modalImg = document.getElementsByClassName("modal-img")[0]
Why does this work?:
// Insert the image into the modal
for (i = 0; i < img.length; i++) {
img[i].addEventListener("click", function () {
modal.style.display = "block"
modalImg.src = this.src
})
}
And this doesn't? (nothing happens when I click the images):
// Insert the image into the modal
img.forEach(function (element) {
element.addEventListener("click", function () {
modal.style.display = "block"
modalImg.src = this.src
})
})
Just for future reference, what would be the best way/syntax to loop through an array of elements to work with event handlers? Is there any to achieve this using the 'img.onclick...' syntax?