The lightbox collects its links once, when it is created. Photos that arrive later — through a “load more” button, infinite scrolling or a filter — are not part of it: clicking them opens the image file directly, and the counter shows the old total.
Two public methods solve this: refresh() for pages that grow, and destroy() for views that disappear.
refresh() destroys the lightbox and builds it again from the original selector, picking up every link that matches now. Call it after the new markup has been inserted:
var lightbox = new SimpleLightbox('.gallery a');
document.querySelector('.load-more').addEventListener('click', function () {
fetch('gallery-page-2.html')
.then(function (response) { return response.text(); })
.then(function (html) {
document.querySelector('.gallery').insertAdjacentHTML('beforeend', html);
lightbox.refresh();
});
});
Because it rebuilds from the selector, refresh() only works when the lightbox was created with a selector string. Passing elements instead throws an error on refresh.
The gallery starts with one photo. Open it and note the counter, then load two more and open it again:
Behind the button there is no request at all: the two extra photos wait in a <template> element and are copied into the grid. That is exactly the moment when a real page would call refresh() after its own Ajax response has been inserted.
When a view is removed, call destroy(). It removes the event listeners and the lightbox markup from the document, so nothing keeps references to elements that no longer exist. Create a new instance when the view is shown again:
var lightbox = null;
function onGalleryMounted() {
lightbox = new SimpleLightbox('.gallery a');
}
function onGalleryUnmounted() {
if (lightbox) {
lightbox.destroy();
lightbox = null;
}
}
By default the lightbox shows an alert when an image cannot be loaded and moves on to the next one. On dynamic pages it is usually better to stay quiet and log the problem:
var lightbox = new SimpleLightbox('.gallery a', { alertError: false });
lightbox.on('error.simplelightbox', function (e) {
console.warn('Image could not be loaded', e);
});
Three options influence how the lightbox behaves on pages that change a lot. A typical gallery never needs them, but they are the first place to look when browsing feels slow or the back button does something unexpected.
preloading loads the previous and next image in the background. Keep it on for smooth browsing; switch it off for galleries of very large files on mobile connections.history lets the browser's back button close the lightbox instead of leaving the page. If your router reacts to the same history entries, test both together.uniqueImages ignores a second link to the same image, for example a thumbnail and a text link that point to one photo.