I have X
and Y
scroll values in percentage (values spanning from 0 to 100) and I want to scroll the page to that location. I am receiving the percentage values from an API call.
function scrollPageByGivenPercentage(percentageX, percentageY) {
// ... scroll by percentage ...
//window.scrollTo(percentageX, percentageY);
}
The above function scrolls in pixels and it doesn't do the job. What I tried using is this:
function scrollPageByGivenPercentage(percentageX, percentageY) {
var yScrollInPx = document.body.documentElement.clientHeight * percentageY;
window.scrollTo(0, yScrollInPx);
}
My guess is clientHeight
is the wrong property. Tried offsetHeight
as well.
I get the calculate the percentages from this question:
I have this function to receive the current scroll value in percentage:
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
return (h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight) * 100;
}