What would be the mathematical formula to calculate (regardless of the
scrollHeight
of the document) how far the bottom of the scrollbar i
0
to 100
relative to scroll position:document.onscroll = function(){
var pos = getVerticalScrollPercentage(document.body)
document.body.innerHTML = "<span>" + Math.round(pos) + "%<span>"
}
function getVerticalScrollPercentage( elm ){
var p = elm.parentNode
return (elm.scrollTop || p.scrollTop) / (p.scrollHeight - p.clientHeight ) * 100
}
body{ height:2000px }
span{ position:fixed; font:5em Arial; color:salmon; }
● Difference between scrollHeight & clientHeight
When you scroll to the bottom, the final position value is equal to the height of your document minus the height of one screen (viewport). So if you compute:
scrollPositionRelative = scrollPosition / (documentHeight - viewportHeight);
The values will be in the range 0-1 as expected.
Here's the function used in the example given at the end.
function getScrollPosition () {
var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); // Viewport height (px)
var scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; // Current scroll position (px)
var documentHeight = $(document).height(); // Document height (px)
var scrollPositionRelative = scrollPosition / (documentHeight - viewportHeight); // The document height is reduced by the height of the viewport so that we reach 100% at the bottom
return {
documentHeight: documentHeight,
relative: scrollPositionRelative,
absolute: scrollPositionRelative * documentHeight // Yields an "average" pixel position
};
}
See it in action: http://jsbin.com/tawana/1/