I have an app with content that should be loaded when the user scrolls down (like Twitter/Facebook...).
I'm trying to detect when to load more data based on scroll events and the current scroll position.
I've read this post: https://stackoverflow.com/a/3898152/82609
if($(window).scrollTop() + $(window).height() == $(document).height()) {
console.error("bottom!");
}
This nearly works but in my case when I scroll to the bottom I have
$(window).scrollTop() + $(window).height() > $(document).height()
How is it possible that window scrolltop + window height is greater than height? It is not so much greater, just a little bit.
console.error("$(window).scrollTop() + $(window).height()=",$(window).scrollTop() + $(window).height()," VS $(document).height()",$(document).height());
// It gives me in the console:
$(window).scrollTop() + $(window).height()= 877 VS $(document).height() 872
Very often, when I have scrolled totally to the bottom I get some extra pixels that comes from nowhere. Can someone explain this?
I'm trying to compute the percentage of scrolled content in a container:
getScrollPercentage: function(scrollableElementSelector) {
var scrollableElement = $(scrollableElementSelector);
// This is the number of hidden pixels of the scrollable element inside its container
var hiddenHeigth;
if ( scrollableElementSelector === window ) {
hiddenHeigth = $(document).height() - $(window).height();
} else {
hiddenHeigth = scrollableElement[0].scrollHeight - scrollableElement.outerHeight();
}
// This is the number of scrolled pixels
var scrolledHeight = scrollableElement.scrollTop();
if ( hiddenHeigth < scrolledHeight ) {
//throw new Error("hiddenHeigth "+hiddenHeigth+" < scrolledHeight " +scrolledHeight + " -> Impossible unless you didn't use this function correctly");
}
var scrollPercent = ( scrolledHeight / hiddenHeigth ) * 100;
if ( this.debug ) {
console.debug("hiddenHeigth=",hiddenHeigth,"scrolledHeight=",scrolledHeight,"scrollPercent=",scrollPercent);
}
return scrollPercent;
}
This function works pretty well, except when I scroll to the bottom, I often get up to 103%
-> Not a big deal for my usecase but I'm trying to understand the problem.