How to fix scrollIntoView scrolling too far with JavaScript?

Sometimes, we want to fix scrollIntoView scrolling too far with JavaScript.

In this article, we’ll look at how to fix scrollIntoView scrolling too far with JavaScript.

How to fix scrollIntoView scrolling too far with JavaScript?

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.

Conclusion

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