Smoothly Scroll to Element in JavaScript

- 1 minute read

There are numerous cases where we might want to scroll to another part of a web page, such as when the user presses a button.

While you can set the page’s scroll position and instantly “teleport” there, I recommend using smooth scrolling instead.

This generally improves the user experience and makes the scroll event much easier to follow.

This function is passed a DOM query selector and will smoothly scroll to its position:

const scrollTo = (element) => {
    document.querySelector(element).scrollIntoView({
        behavior: `smooth`,
    });
};

Here’s a few examples of how it could be used:

scrollTo(`#example`);

scrollTo(`.example`);

scrollTo(`h1`);

It is very important to note that you should make sure that there are no duplicate instances of the selector you pass to scrollTo, because you’ll otherwise experience some unexpected behavior.

I’d also like to note that this is distinct from the scroll-behavior CSS property, yet similar in function.

Link to this section Conclusion

That’s all! I’ve found this function to be a real life saver. There’s typically no need to throw a bunch of fancy CSS at the problem or do anything much more complex.

Thanks for reading!