0

I'm trying to code an e-commerce webpage simulation which you can browse through the images of a certain product and open a lightbox display of the image that is being shown on the page. I'm stuck at the point where it should display the image that's been selected by user in lightbox. It only works when the first image is shown on the page but when I switch to another image the event listener doesn't switch with the image.

What i've tried:

var images = document.querySelectorAll(".productImage");

var imageIndex = 0;

document.onload = displayImage(imageIndex);

function displayImage(n) {
  imageIndex = n;
  images.forEach((image) => {
    image.removeAttribute("id");
    image.classList.add("imageHidden");
  });
  images[n].classList.remove("imageHidden");
  images[n].id = "productImageActive";
}

var imageDisplayed = document.querySelector("#productImageActive");
var lightbox = document.querySelector("#lightbox");

imageDisplayed.addEventListener("click", openLightbox);

function openLightbox() {
  lightbox.style.display = "flex";
}

The problem is it does not add the event listener to the element that has the id of "productImageActive". Instead the event listener is stuck in the first element that had the id. So it opens the lightbox when clicked on the first image only and not the other images.

I've checked the HTML logs and it actually updates the id of the elements and it gives the right attributes but the event listeners shown in devtools claim that only the first element has the event listener and not the element that actually has the id.

Sannora
  • 51
  • 3
  • JavaScript doesn't do time travel. You get an element using its ID. You then bind an event listener to **that** element. There's nothing that would change where the event listener is bound. Use event delegation instead. See the duplicate. – Quentin Oct 05 '22 at 10:45

0 Answers0