I'm totally new to web development, especially JavaScript, and I'm currently working on an image gallery that opens a lightbox when an image is clicked. This part is working fine. However, I want to have more than one gallery on the same page, each with its own set of images. The problem arises when I click an image from the second gallery; it opens the lightbox tied to the first gallery instead! I'm not the best with code, so any help would be appreciated! Here's my [CodePen link](https://codepen.io/Ghost-Pixels/pen/qEOLxYV) for reference. Thanks!
2 Answers
It looks like your JS is targeting all images globally, which is why the wrong lightbox opens. You should scope your lightbox to each gallery. Try using specific IDs for each gallery and modify your JavaScript to select images only from the clicked gallery. For example, set up your HTML like this:
```




```
Then, in your JS, add click events to the images within each gallery to call a function that only uses images from that gallery. This helps keep the galleries independent! You could do something like this:
```javascript
const galleries = document.querySelectorAll('.gallery');
galleries.forEach(gallery => {
const images = gallery.querySelectorAll('img');
images.forEach(img => {
img.addEventListener('click', () => {
openLightbox(images, img);
});
});
});
```
This should get you going in the right direction!
Consider simplifying by using a lightbox library if you want a quick solution without getting into too much code yourself. There are great options like [fslightbox](https://fslightbox.com/) or [Lightbox2](https://lokeshdhakar.com/projects/lightbox2/). These take care of the heavy lifting and let you focus on learning!
I’m really trying to learn, though. Using libraries feels like skipping ahead!