The problem:
What would be the mathematical formula to calculate (regardless of the
scrollHeight
of the document) how far the bottom of the scrollbar is from it's total bottom (which would be the end of the page). So, for example, when the scrollbar is at the top, I would say the distance in percentages of the bottom of it, from the bottom of the document, would be 0%, and when it's totally scrolled all the way (vertically), it would be 100%.
My goal:
My goal is to calculate how many pixels there are between the bottom and a specific position which is, let's say 3%, relative to the viewport, above that bottom. Again, the document height should mean nothing. 3% are 3% if it's relative to the viewport.
Known variables:
var P = 3 // in %
var totalHeight = document.documentElement.scrollHeight;
var viewportHeight = document.documentElement.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:
The values will be in the range 0-1 as expected.
Here's the function used in the example given at the end.
See it in action: http://jsbin.com/tawana/1/
Returns a number between
0
to100
relative to scroll position:● Different between
scrollHeight
&clientHeight