trvswgnr / bs5-lightbox

A pure JS lightbox gallery plugin for Bootstrap 5 based on the Modal and Carousel components
https://trvswgnr.github.io/bs5-lightbox/
MIT License
129 stars 28 forks source link

Use with dynamically loaded images #15

Closed lleibovici closed 2 years ago

lleibovici commented 2 years ago

I have a page that uses ajax to load the images. How do I delay the initalization of bs5-lightbox so that the lightbox fub=nctionality can be applied to the loaded images. On bootstrap 4 I used this: $(document).on('click', '[data-toggle="lightbox"]', function (event) { event.preventDefault(); $(this).ekkoLightbox(); });

is threre a variation of this that i can use?

trvswgnr commented 2 years ago

@lleibovici you could do something like this:

Remove the original event listener:

document.querySelectorAll(Lightbox.defaultSelector).forEach(el => el.removeEventListener('click', Lightbox.initialize));

Then add the jQuery event listener:

$(document).on('click', Lightbox.defaultSelector, Lightbox.initialize);

or, in vanilla JS:

document.addEventListener('click', event => {
    const target = event.target.closest(Lightbox.defaultSelector);
    if (target) {
        Lightbox.initialize.apply(target, [event]);
    }
});

If using the CDN version replace Lightbox with bootstrap.Lightbox.

I might make this the default behavior in a future version.

Let me know if that works for you!

lleibovici commented 2 years ago

That worked fine. Thanks very much. I very much appreciate your hard work.