Skip to content

Instantly share code, notes, and snippets.

@xocasdashdash
Created August 24, 2014 13:42
Show Gist options
  • Save xocasdashdash/3ccace95c3215cdfbfae to your computer and use it in GitHub Desktop.
Save xocasdashdash/3ccace95c3215cdfbfae 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();
}
}
});
@anybug
Copy link

anybug commented Apr 17, 2018

still very helpful in 2018, thanks ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment