Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138163

Scroll by given vertical scroll percentage in JavaScript

$
0
0

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;
}

Viewing all articles
Browse latest Browse all 138163

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>