I have a script that loads new products when a user scrolls to the bottom. The script works but I have two problems with it though. That’s
a) the script loads page1 twice
b) the script loads all pages at once instead of one at the time
Does anyone know a solution? I have limited knowledge so any help greatly appreciated.
My script
<script type="text/javascript">
$(document).ready(function(){
// var pageSize = {{ collection.limit }};
var currentPage = 1;
var collectionPages = {{ collection.pages }};
var category = '{{ collection.internal.url }}';
// Appends the new product to the UI
var appendProduct = function(product, id) {
$('<div class="product"></div>')
.html(product)
.appendTo($(".productsGrid"));
var i = 1;
$('.product').each(function() {
if(i++ % 3 == 0)
$(this).addClass('last');
});
};
// Load the next products page
var loadProducts = function() {
var url = "http://shop.com/"+category+"/page"+currentPage+".ajax";
$.getJSON(url,function(data) {
$.each(data.products, function(index, product) {
appendProduct('<a href="'+product.url+'" title="'+product.fulltitle+'">' +
'<img src="'+product.image+'" width="180" height="150" alt="'+product.fulltitle+'" title="'+product.fulltitle+'"'+'</a>' +
'<div class="info"><h3><a href="'+product.url+'" title="'+product.fulltitle+'">'+product.fulltitle+''+'</a></h3>' +
'<div class="price">'+product.price.price_money+''+'</div>' +
'<div class="gridAddToCart"><a class="button grey" href="'+product.url+'" title="'+product.fulltitle+'" rel="nofollow">'+'<span>{{ 'Details' | t }}</span></a>' +
'<div style="margin-top:2px;"></div>' +
'<a class="opener button blue" href="http://meules1.webshopapp.com/cart/add/'+product.vid+'" title="'+product.fulltitle+'" rel="nofollow"><span>{{ 'Add to cart' | t }}</span></a>'
+ '<div class="clear"></div>' +
'</div><div class="clear"></div></div>'
);
});
// We're done loading the products, so hide the overlay and update the UI
$("#overlay").fadeOut();
});
};
// First time, directly load the products
loadProducts();
// Append a scroll event handler to the container
$(window).scroll(function() {
// activate new load when scrollbar reaches 150 pixels or less from the bottom
if($(window).height() + $(window).scrollTop() >= $(document).height() - 350) {
if(currentPage <= collectionPages) {
$("#overlay").fadeIn();
loadProducts();
currentPage++;
}
}
});
});
</script>
Problem A
You’re incrementing the page number after you run the
loadProductsfunction:You should try this:
Problem B
The code you execute at
window.scrollis probably firing multiple many times when the user gets to the bottom, meaning all the pages are loaded straight away. One way to get around this could be to only run the code if your overlay is not visible:Alternatively, you could set a global variable like
var loading_page = false. Switch this to true when you start loading a page, switch it back to false once the new page is fully loaded, and only allow the scroll code to execute when theloading_pagevariable is false.