aitor
aitor

Reputation: 2735

Lightgallery v2 multiple instances

This library has an example to build a gallery based on element ID:

lightGallery(document.getElementById('lightgallery'), {
    plugins: [lgZoom, lgThumbnail],
    speed: 500,
    ... other settings
});

I want to build several instances based on a class. I tried to iterate a collection:

import lightGallery from 'lightgallery';

let galleries = document.getElementsByClassName('lightbox');

for (const gal of galleries) {
  lightGallery(gal), {
    selector: 'a',
  }
}

But it doesn't work. I get this error (despite the HTML element has an a element with img inside): lightGallery :- data-src is not provided on slide item 1. Please make sure the selector property is properly configured.

How can I build these galleries from an HTML collection?

Upvotes: 1

Views: 735

Answers (2)

Brandon H
Brandon H

Reputation: 178

Here is what worked for me.

<script type="text/javascript">
              
   document.addEventListener("DOMContentLoaded", function () {
      // Get all elements with the class 'lightGal'
      let galleries = document.getElementsByClassName('lightGal');
    
      // Loop through each gallery
      for (let i = 0; i < galleries.length; i++) {
        // Assign a unique ID to each gallery
        galleries[i].id = 'gal' + i;
    
        // Initialize lightGallery for the specific gallery
        lightGallery(document.getElementById('gal' + i), {
          selector: 'a', // This targets the child <a> elements
          licenseKey: 'YOUR LICENSE KEY',
          speed: 500,
          mode: 'lg-fade',
        });
      }
   });
    
</script>

Upvotes: 0

aitor
aitor

Reputation: 2735

Just creating IDs on the way:

let galerias = document.getElementsByClassName('lightbox');

for (let i = 0; i < galerias.length; i++) {

  galerias[i].id = 'gal' + i; // <-------------------- creating IDs here

  lightGallery(document.getElementById('gal' + i), {
    selector: 'a',
  });

}

Upvotes: 1

Related Questions