How to add click event listener on images of gallery, when they are lazy loading?

496 views Asked by At

I am using inline gallery of light gallery JS and trying to add click event listener on images of gallery. For that, I am using this event- lgAfterOpen.

I am not able to get all the image tags as the images are lazy loading, using this lgAfterOpen event, till then I get only first image loaded in DOM. How should I keep lazy loading and also able to put event listener on all images of gallery?

Code Sample I was trying:

lgContainer.addEventListener('lgAfterOpen', function(e){
  let images = document.getElementsByClassName('lg-object lg-image'); // expecting to return all images
  for (image of images) image.addEventListener('click', function() { /* code here */ }) // geting only first image here. 
})
1

There are 1 answers

0
Rahul Singh On BEST ANSWER

Finally, I figured this out with by adding the event listener to the parent div of images - i.e div with .lg-item, as I can find them for all images in DOM before image are loaded. I hope this will be helpful for someone.