Another approach could be this: place the button at the end of the page so that when scrolling you can check whether the button enters the viewing area and trigger a click
.In order not to show the same messages every time, change the getmore id with the last id obtained from ajax call
$.fn.isInViewport = function () { var elementTop = $(this).offset().top; var elementBottom = elementTop + $(this).outerHeight(); var viewportTop = $(window).scrollTop(); var viewportBottom = viewportTop + $(window).height(); return elementBottom > viewportTop && elementTop < viewportBottom; }; if ($('.getmore').isInViewport()) { $('.getmore').click(); } $(window).scroll(function(){ if ($('.getmore').isInViewport()) { $('.getmore').click(); } $('body').on('click','.getmore',function(){ var lastelement = $(this ).attr('id'); $.ajax({ type : 'GET', url : 'getmore.php', data : 'lastelement='+lastelement, beforesend : function(){ $('.getmore').html('loading....'); }, success: function(data){ $('.getmore').attr('id', (lastelement + $('.getmore').attr('id'))); $('#recs') .append(data) ; } }); }); });
when your ajax answer is empty than you can remove the .getmore button
As suggested in another answer, introducing the isLoadingNewPage variable is good practice.
source share