I am trying to load more items on-scroll. The code works and the user reaches the bottom of the page. Every time the user scrolls to the bottom of the page, 9 items are loaded.
The issue appears when I try to load 9 items before the user reaches the bottom of the page. Then wait for those items to be loaded and then check again the condition (currentScroll >= goal).
At this point as soon as the condition is TRUE (currentScroll >= goal) all items are loaded at once. I am guessing that this is happening because the currentScroll variable keeps counting while scrolling and the first group of items has not been yet loaded. As a result the $(document).height() is still the same, which affect the goal variable: var goal = $(document).height() - $(window).height();
I tried to use a while loop (see the commented section at my code) but the code crashes.
Is there any way to make the program wait for the group of items (9 items) to be loaded when the condition is TRUE and then check again?
$(window).scroll(function() {
var currentScroll = $(window).scrollTop();
var goal = $(document).height() - $(window).height(); // Bottom of the page
goal = goal*0.5; // Load more items before reach bottom of the page
// The following parts check if all the items are loaded. That works!!
var result_count = document.getElementsByClassName('yacht-count')[0].innerHTML
total_results_to_show = group_of_villas_showed*results_to_show;
if(result_count/total_results_to_show<=1){
goal = currentScroll*2;
console.log("Finish");
}
// Check if the current scroll is greater than the setted goal
if (currentScroll >= goal){
console.log("start loading villas");
ajaxGet(guests_value,destinations_value,sort_by,current_page);
current_page++;
group_of_villas_showed+=1;
console.log("loading villas");
}
// With the use of this Loop program crashes
/*
while(currentScroll >= goal){
goal = $(document).height() - $(window).height();
var currentScroll = $(window).scrollTop();
goal = goal*0.5;
}
*/
});
ajaxGet = (guests_value,destinations_value,sort_by,page, replace = false) => {
$.ajax({
type: 'GET',
url: ajax_url,
data: {
guests: guests_value,
destination: destinations_value,
sort_by: sort_by,
page:page,
},
dataType: 'json',
beforeSend: function(){
$('#loading-image').removeClass('hide');
$('.yachts-search-page').addClass('loading-more');
},
success: function (data) {
//console.log('ajax success');
$('.yachts-search-page').removeClass('loading-more');
$('#loading-image').addClass('hide');
if(replace){
$('body .load-more-wrapper').show();
$('body .yachts-inner').html(data.content);
current_page = 1;
}
else
$('body .yachts-inner').append(data.content);
$('body .yacht-count').text(data.yacht_count);
newQueryString(guests_value,destinations_value,sort_by,page);
},
error: function(data){
//console.log('error wtf');
}
});
}