Categories
JavaScript Answers

How to fix scrollIntoView scrolling too far with JavaScript?

Spread the love

To fix scrollIntoView scrolling too far with JavaScript, we can call scrolTo with the top position of the element.

For instance, we write

const id = "profilePhoto";
const yOffset = -10;
const element = document.getElementById(id);
const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;

window.scrollTo({ top: y, behavior: "smooth" });

to get the element we want to scroll to with getElementById.

Then we get the y position by adding the top positionb of the element with the pageYOffset and yOffset.

Finally, we call scrollTo with an object with the top position set to y to scroll to the top of the element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *