I am working on loading around 1000 products on a page and thought of following approach of OnScroll
loading.
Below is the approach i am following:
<ul id="productContainer">
</ul>
JQuery:
$(document).ready(function() {
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multipal ajax loads
var total_groups = 5;
$('#productContainer').load("loadmore",
{'group_no':track_load}, function() {track_load++;});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() ==
$(document).height()) {
if(track_load <= total_groups && loading==false){
loading=true;
$.post('store/loadmore',{'group_no': track_load},
function(data){
$("#productContainer").append(data).fadeIn();
track_load++; //loaded group increment
loading = false;
});
}
}
});
});
PHP
$items_per_group = 25;
$get_total_rows = /*count from SQL table*/
$total_groups = ceil($get_total_rows/$items_per_group);
if(isset($_POST)){
$group_number = filter_var($_POST["group_no"],
FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($group_number)){
header('HTTP/1.1 500 Invalid number!');
exit();
}
$position = ($group_number * $items_per_group);
/*PHP Query*/
}
This solution is working pretty well but has following issues:
- Products are loaded only when user scrolls to complete end of the page -
But needed thing is that as soon as user reaches last element of current view then next products shall be loaded.
- After scrolling complete bottom of page first time and then i user scroll up then also, AJAX call is fired.
How can i prevent these issues and then i will have great solution.
I tried below solution also:
if($(window).scrollTop() + $(window).height() ==
$(document).height()-`200[height of footer]`) {}
Second solution
var end = $("#copyright").offset().top;<br/>
var viewEnd = $(window).scrollTop() + $(window).height();<br/>
var distance = end - viewEnd;<br/>
if(distance <400{load products ajax}
But none of it seems working as expected