Infinite scrolling
Infinite scrolling is a web-design technique that loads content continuously as the user scrolls down the page, eliminating the need for pagination. Let`s see how we can implement infinite scrolling with lightGallery
HTML Structure
<div id="infinite-scroll-gallery">
<a href="img/img1.jpg">
<img src="img/thumb1.jpg" />
</a>
<a href="img/img2.jpg">
<img src="img/thumb2.jpg" />
</a>
...
</div>
Javascript
const $infiniteScrollGallery = document.getElementById(
'infinite-scroll-gallery',
);
const lg = lightGallery($infiniteScrollGallery, {
speed: 500,
});
Since, we are already using jQuery on this website, let’s make use of jQuery to find out when user scrolls till the bottom of the page. Or if you prefer, you can use any of the JavaScript infinite scrolling plugin.
const $window = $(window);
$window.scroll(function () {
if ($window.scrollTop() >= $(document).height() - $window.height() - 10) {
// User scrolled till the bottom the page
}
});
Then, append thumbnails to the existing gallery.
const thumbnails = `
<a href="img/img1.jpg">
<img src="img/thumb1.jpg" />
</a>
<a href="img/img2.jpg">
<img src="img/thumb2.jpg" />
</a>
`;
$('#infinite-scroll-gallery').append(thumbnails);
Finally, you need to destroy the current lightGallery instance and re-initiate lightGallery
lg.destroy();
setTimeout(() => {
lg = lightGallery($infiniteScrollGallery, {
speed: 500,
});
}, 500);
That’s it. Here the full example
const $infiniteScrollGallery = document.getElementById(
'infinite-scroll-gallery',
);
let infiniteScrollingGallery = lightGallery($infiniteScrollGallery, {
speed: 500,
});
const thumbnails = `
<a href="img/img3.jpg">
<img src="img/thumb3.jpg" />
</a>
<a href="img/img4.jpg">
<img src="img/thumb4.jpg" />
</a>
`;
const $window = $(window);
let shouldReInit = true;
$window.scroll(function () {
if ($window.scrollTop() >= $(document).height() - $window.height() - 10) {
$('#infinite-scroll-gallery').append(images);
infiniteScrollingGallery.refresh();
}
});