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.