Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to use a percent value in window.scrollTo()

I have a window.scrollTo() function on my website. It uses just a number value (or pixels) which works fine in a larger-sized window but does not scroll where I want on mobile devices. Instead, I want to use a percent value (or some dynamic unit) so it scrolls where I want on all devices.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can measure the screen height and then divide by 100 and with it, you get the unit with percentage.

let unit = document.documentElement.scrollHeight / 100;

const onScroll = () => {
  console.log(unit)
  window.scrollTo({ top: 30 * unit });
}
body {
   height: 2000px;
}
<button onclick="onScroll()">Scroll</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading