Categories
JavaScript Answers

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

Spread the love

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.

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 *