Skip to content

Instantly share code, notes, and snippets.

@git-willie
Created November 18, 2020 01:46
Show Gist options
  • Select an option

  • Save git-willie/e639cbb57e3636369b88f034eda506b1 to your computer and use it in GitHub Desktop.

Select an option

Save git-willie/e639cbb57e3636369b88f034eda506b1 to your computer and use it in GitHub Desktop.
Infinitely loads products on to a collection page
$(document).ready(function() {
var collectionURL = $('.collection-main').attr('data-collection-url');
var collectionPages = $('.collection-main').attr('data-collection-pages');
var ajaxLoadPageIndex = 2;
var ajaxIsRunning = false;
$(window).scroll(function(){
if ($(document).scrollTop() > 500) {
infiniteLoadProducts();
}
});
});
function infiniteLoadProducts() {
if (ajaxLoadPageIndex <= collectionPages) {
ajaxLoadProducts();
}
}
function ajaxLoadProducts() {
if (!ajaxIsRunning) {
ajaxIsRunning = true;
$('.collection-main__loader').fadeIn();
$.ajax({
type: 'GET',
url: collectionURL + '?page=' + ajaxLoadPageIndex,
success: function(data) {
var filteredData = $(data).find('.product');
var currentScrollPosition = $(document).scrollTop();
var i = 1;
filteredData.insertBefore($('.collection-main__loader'));
$(document).scrollTop(currentScrollPosition);
$('.product').each(function(){
$(this).attr('data-product-index', i++);
});
++ajaxLoadPageIndex;
},
complete: function() {
ajaxIsRunning = false;
infiniteLoadProducts();
$('.collection-main__loader').fadeOut();
},
dataType: 'html'
});
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment