I need help creating endless scrolling for GIFs using the Giphy API, similar to what you see on Facebook when adding media to posts. My current setup only loads 25 GIFs and stops there, even though I want it to keep loading more as the user scrolls down. I know the API supports pagination with limit and offset parameters, but I can’t get the continuous loading to work properly. Here’s my current implementation:
$(document).ready(function() {
let currentPage = 0;
let itemsPerPage = 25;
let isLoading = false;
$('#gifContainer').on('scroll', function() {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
loadMoreGifs();
}
});
function searchGifs(query) {
if (!query) return;
let apiOffset = itemsPerPage * currentPage;
if (isLoading) return;
isLoading = true;
$.get({
url: 'https://api.giphy.com/v1/gifs/search',
data: {
q: query,
api_key: 'your_api_key',
limit: itemsPerPage,
offset: apiOffset
}
}).done(function(response) {
if (response.meta.status === 200 && response.data.length) {
$('#gifContainer').empty();
response.data.forEach(function(gif) {
let imgElement = $('<img>').attr({
src: gif.images.preview_gif.url,
'data-full': gif.images.original.url,
alt: 'animated gif'
});
$('#gifContainer').append(imgElement);
});
currentPage++;
}
isLoading = false;
});
}
});
The scrolling detection works but it doesn’t trigger additional API calls. What am I missing to make this work like an infinite scroll?