G.Dimov
G.Dimov

Reputation: 2393

Scroll by given vertical scroll percentage in JavaScript

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

Upvotes: 4

Views: 579

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Get the total height of the document, work out the percentage you need in px then apply that to window.scrollTo(). Try this:

var scrollYPercent = 0.25;
var scrollYPx = document.documentElement.scrollHeight * scrollYPercent;
window.scrollTo(0, scrollYPx);
html, body { height: 1000px; }
p { margin-top: 400px; }
<p>Note the scroll position -></p>

Upvotes: 1

Related Questions