Categories
JavaScript Answers

How to smooth scroll anchor links with JavaScript?

Spread the love

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.

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 *