Categories
JavaScript Answers

How to use JavaScript scrollIntoView to do smooth scroll with offset?

Spread the love

Sometimes, we want to use JavaScript scrollIntoView to do smooth scroll with offset.

In this article, we’ll look at how to use JavaScript scrollIntoView to do smooth scroll with offset.

How to use JavaScript scrollIntoView to do smooth scroll with offset?

To use JavaScript scrollIntoView to do smooth scroll with offset, we can call scrollTo with an object that has the top and behavior properties.

For instance, we write

const element = document.getElementById("targetElement");
const headerOffset = 45;
const elementPosition = element.getBoundingClientRect().top;
const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

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

to call scrollTo with an object to set the top property to the top offset position.

And we set behavior to 'smooth' to do smooth scrolling.

We get offsetPosition by getting the computed top position of the element with getBoundingClientRect and add window.pageYOffset - headerOffset to it.

Conclusion

To use JavaScript scrollIntoView to do smooth scroll with offset, we can call scrollTo with an object that has the top and behavior properties.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.