I am just wondering how can i implement more data on scroll only if the div.loading is visible.
Usually we look for page height and scroll height, to see if we need
Improving on @deepakssn answer. There is a possibility that you want the data to load a bit before we actually scroll to the bottom.
var scrollLoad = true;
$(window).scroll(function(){
if (scrollLoad && ($(document).height() - $(window).height())-$(window).scrollTop()<=800){
// fetch data when we are 800px above the document end
scrollLoad = false;
}
});
[var scrollLoad] is used to block the call until one new data is appended.
Hope this helps.
I suggest using more Math.ceil for avoid error on some screen.
Because on a few different screens it's not absolutely accurate
I realized that when I console.log.
console.log($(window).scrollTop()); //5659.20123123890
And
console.log$(document).height() - $(window).height()); // 5660
So I think we should edit your code to
$(window).scroll(function() {
if(Math.ceil($(window).scrollTop())
== Math.ceil(($(document).height() - $(window).height()))) {
// ajax call get data from server and append to the div
}
});
Or Allow load data from server before scroll until bottom.
if ($(window).scrollTop() >= ($(document).height() - $(window).height() - 200)) {
// Load data
}
Have you heard about the jQuery Waypoint plugin.
Below is the simple way of calling a waypoints plugin and having the page load more Content once you reaches the bottom on scroll :
$(document).ready(function() {
var $loading = $("<div class='loading'><p>Loading more items…</p></div>"),
$footer = $('footer'),
opts = {
offset: '100%'
};
$footer.waypoint(function(event, direction) {
$footer.waypoint('remove');
$('body').append($loading);
$.get($('.more a').attr('href'), function(data) {
var $data = $(data);
$('#container').append($data.find('.article'));
$loading.detach();
$('.more').replaceWith($data.find('.more'));
$footer.waypoint(opts);
});
}, opts);
});