Skip to content

Instantly share code, notes, and snippets.

@aimeric
Forked from xocasdashdash/infinite-scroll.js
Created January 23, 2017 00:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aimeric/ff55e1d316289c409b8beb5aee745c05 to your computer and use it in GitHub Desktop.
Save aimeric/ff55e1d316289c409b8beb5aee745c05 to your computer and use it in GitHub Desktop.
Simple infinite scrol with jQuery and a Symfony2 backend
is_processing = false;
last_page = false;
function addMoreElements() {
is_processing = true;
$.ajax({
type: "GET",
//FOS Routing
url: Routing.generate('route_name', {page: page}),
success: function(data) {
if (data.html.length > 0) {
$('.selector').append(data.html);
page = page + 1;
//The server can answer saying it's the last page so that the browser doesn't make anymore calls
last_page = data.last_page;
} else {
last_page = true;
}
is_processing = false;
},
error: function(data) {
is_processing = false;
}
});
}
$(window).scroll(function() {
var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();
//Modify this parameter to establish how far down do you want to make the ajax call
var scrolltrigger = 0.80;
if ((wintop / (docheight - winheight)) > scrolltrigger) {
//I added the is_processing variable to keep the ajax asynchronous but avoiding making the same call multiple times
if (last_page === false && is_processing === false) {
addMoreElements();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment