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

Advertisements

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 :

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>

Leave a ReplyCancel reply