JavaScript events error

Hello, I have the following snippet of code in codepen
The problem is that I make galleryImg to point to all tags. But when adding event listeners to show to gallery (like this) it doesn’t respond.
Please tell me where it went wrong! Thank you

It looks like galleryImg is a collection, not a HTML element;
therefore galleryImg does not have a .onclick property.
So you could loop through the elements in the collection to set the .onclick one element at a time.

for (let img of galleryImg) {
  img.onclick = function () {
    gallerySlideshow.classList.add("active");
  };
}

An alternative would be to use jQuery or something similar.

Thank you! One follow up question: if I change the code to

galleryImg[1].onclick = function() {
    gallerySlideshow.classList.add("active");
}

If I click on the second image (corresponding to galleryImg[1]), the gallery pops up. But when I close the gallery, and click on the second image one more time, the gallery wouldn’t pop up again. Any comment on this?

You may need to remove the classes in some of these event listener functions.

For example:

galleryImg[1].onclick = function() {
    gallerySlideshow.classList.remove("hide");
    gallerySlideshow.classList.add("active");
}

Here’s a fuller version:

galleryClose.onclick = function () {
  gallerySlideshow.classList.remove("active");
  gallerySlideshow.classList.add("hide");
};

for (let img of galleryImg) {
  img.onclick = function () {
    gallerySlideshow.classList.remove("hide");
    gallerySlideshow.classList.add("active");
  };
}

Although, in your case, just toggling the class may be enough for what you want to do:

for (let img of galleryImg) {
  img.onclick = function () {
    gallerySlideshow.classList.toggle("active");
  };
}