0

I'm using the following function to calculate and save the percentage of how much of a web page I have scrolled:

const getPercentRead = () => {
  const h = document.documentElement,
    b = document.body,
    st = "scrollTop",
    sh = "scrollHeight";
  return ((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100;
}

After refreshing the page, I want to use the output of this function and the current window height to scroll myself to the last saved location.

This is my current attempt at doing this:

const scrolled = (percentRead / windowHeight) * 100;
window.scrollTo(0, scrolled);

However, this does not take me to the correct scroll position. I'd appreciate any help you can give on this.

Thank you!

Joshua L
  • 23
  • 1
  • 6

1 Answers1

0

If you don't need to use percentages, this solution will work.

Save this value:

var x = window.pageYOffset;

Then scroll to it:

window.scrollTo(0, x);
Dan Mullin
  • 4,285
  • 2
  • 18
  • 34
  • Right. The issue is I will need to turn it into a percentage for use in the UI. I also like the idea of saving a percentage, because I may come back to view the webpage on a different device, so saving the pageYOffset won't work there. – Joshua L Aug 06 '20 at 16:32