Sentry Answers>JavaScript>

How do I scroll to the top of the page in JavaScript?

How do I scroll to the top of the page in JavaScript?

Richard C.

The ProblemJump To Solution

How do you scroll to the top of the page in JavaScript? You might want to do this programmatically to, for example, add a button to the bottom of the page that a user can click to immediately return to the top.

The Solution

If you want to move the page to a specific coordinate programmatically the best solution is to use scrollTo:

Click to Copy
globalThis.scrollTo({ top: 0, left: 0, behavior: "smooth" });

Note:

  • We use globalThis instead of window because globalThis works in both Node.js and browsers, instead of global or window.
  • behavior can be smooth, instant, or auto (which is set in CSS). smooth is best for most web pages, but for work apps where users might scroll up hundreds of times a day you’ll want to use instant.
  • top and left are the number of pixels away from the top left corner of the page.
  • An older alternative you might see on some pages is globalThis.scrollTo(0, 0);. There’s no reason to use this anymore, but it isn’t harmful.

Scroll to Specific Headings

If you want to scroll the page to a specific section, where the absolute coordinate might change as the page layout changes, it’s better to use an anchor.

Click to Copy
document.getElementById("title").scrollIntoView({ behavior: "smooth" });

You need an element with an id for this to work, like <span id="title">This is the top of my page</span>.

Add a Button to Your Page That Scrolls to the Top

Instead of scrolling automatically, if you want the user to be able to click a button to scroll up, you can add the following to your HTML:

Click to Copy
<span id="title">This is the top of my page</span> <button onClick="document.getElementById('title').scrollIntoView({ behavior: 'smooth'});"> Back to top </button>

Caution

Be careful if you change the location of the URL bar, like this: document.location.href = "#top";. It may cause problems in a single page app (SPA) if it interferes with the framework’s page history. Test it and see.

  • ResourcesImprove Web Browser Performance - Find the JavaScript code causing slowdowns
  • ResourcesJavaScript Frontend Error Monitoring 101
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty Treats for Web Developers brought to you by Sentry. Web development tips and tricks hosted by Wes Bos and Scott Tolinski

    Listen to Syntax

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.