# Scroll to the Top of a Page Using JavaScript Methods

> Use the scrollTo method with smooth behavior or scrollIntoView to scroll to the top of a page or a specific heading in JavaScript with code examples

**URL:** https://sentry.io/answers/how-do-i-scroll-to-the-top-of-the-page-in-javascript/

---

## The Problem

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`:

```js
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.

```js
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:

```html
<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.

---

*Source: [sentry.io/answers/how-do-i-scroll-to-the-top-of-the-page-in-javascript/](https://sentry.io/answers/how-do-i-scroll-to-the-top-of-the-page-in-javascript/)*
