Sometimes, we want to smooth scroll anchor links with JavaScript.
In this article, we’ll look at how to smooth scroll anchor links with JavaScript.
How to smooth scroll anchor links with JavaScript?
To smooth scroll anchor links with JavaScript, we call the window.scroll method.
For instance, we write
window.scroll({
behavior: "smooth",
left: 0,
top: element.offsetTop,
});
to call scroll with an object that has the behavior property set to 'smooth' to do smooth scrolling.
And we set top to element.offsetTop to scroll to the top of the element.
Conclusion
To smooth scroll anchor links with JavaScript, we call the window.scroll method.