banthagroup / fslightbox

An easy to use vanilla JavaScript plug-in without production dependencies for displaying images, videos, or, through custom sources, anything you want in a clean overlying box.
MIT License
351 stars 30 forks source link

Custom selector for initializing lightbox? #125

Closed seamofreality closed 1 year ago

seamofreality commented 4 years ago

Hey there,

I'm really keen to use your lightbox library but I've run into the limitation that I can't trigger it using a custom selector. Unfortunately I have no influence on the link markup wrapped around the images, so I can't add the data attribute directly. I also wanted to avoid adding the data attribute programmatically if possible.

Is there a way to use a custom selector?

Thanks!

banthagroup commented 4 years ago

No using custom selector is not possible. However you can open lightbox programmatically: https://fslightbox.com/javascript/documentation/how-to-use#programmatically

imitronov commented 4 years ago
require('fslightbox')

function initGallery(selector) {
  const blocks = document.querySelectorAll(`${selector}`)
  if (blocks.length > 0) {
    blocks.forEach(block => {
      const items = block.querySelectorAll('a')
      if (items.length > 0) {
        const lightbox = new window.FsLightbox()
        lightbox.props.sources = []
        items.forEach((item, key) => {
          lightbox.props.sources.push(item.getAttribute('href'));
          item.addEventListener('click', e => {
            e.preventDefault()
            lightbox.open(key)
          })
        });
      }
    })
  }
}

document.addEventListener('DOMContentLoaded', () => {
  if (document.querySelector('.wp-block-gallery')) {
    initGallery('.wp-block-gallery')
  }
})
piotrzdziarski commented 1 year ago

@imitronov provided a programmatic solution. A solution with using solely markup is not possible.