Sroll to Top of Page in JavaScript

- 1 minute read

The following JavaScript snippet uses the built-in window.scrollTo method to scroll to the top of the page:

window.scrollTo(0, 0);

When the above code is run, the user is instantaneously “teleported” to the top of the page.

Link to this section Smoothly scrolling to the top

You can also smoothly scroll to the top by passing an object with a behavior property set to "smooth" as a parameter to window.scrollTo, like this:

    behavior: `smooth`,
    left: 0,
    top: 0,

Link to this section Conclusion

Personally, I almost always set behavior to "smooth" when scrolling the user around the page.

Anyway, I hope one of these quick snippets helped you!