Ethan
Ethan

Reputation: 1637

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.

Upvotes: 0

Views: 1062

Answers (1)

Mina
Mina

Reputation: 17079

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>

Upvotes: 3

Related Questions