Question

Scroll to Top of a Page with JavaScript

Question

How can I use JavaScript to scroll the browser window instantly to the top of the page? I want the scrollbar to jump directly to the top rather than using smooth scrolling.

Short Answer

You will learn how browser scrolling is controlled in JavaScript and how to reliably move the current page viewport to its top position instantly. You will also see how to attach the behavior to a button and avoid common scrolling mistakes.

Concept

A web page can be taller than the visible browser area. The browser therefore maintains a scroll position: how far the viewport has moved from the page's top and left edges.

JavaScript can change that position through the window object. The clearest modern API is window.scrollTo(). It accepts coordinates:

  • top: vertical distance from the top of the document
  • left: horizontal distance from the left of the document
  • behavior: whether movement is instant ("auto") or animated ("smooth")

To reach the top, set top to 0. This matters in real interfaces because long pages often provide a Back to top control after users have read a large amount of content.

Mental Model

Think of the page as a long paper map under a small window. Scrolling moves the map beneath the window.

  • At top: 0, the window is looking at the map's very top edge.
  • At top: 800, the window is looking 800 pixels below the top.

window.scrollTo() tells the browser exactly where to place that window. Asking for top: 0 moves the view back to the start immediately.

Take Quiz

Syntax and Examples

Use window.scrollTo() with a top coordinate of 0:

window.scrollTo({
  top: 0,
  left: 0,
  behavior: "auto"
});

behavior: "auto" uses the browser's normal, non-animated scrolling behavior. In most browsers, this means the viewport jumps immediately.

For a simple vertical page, this shorter form also works:

window.scrollTo(0, 0);

The first 0 is the horizontal position (x or left), and the second is the vertical position (y or top).

Here is an HTML button that performs the action when clicked:

<button id="backToTop" type="button">Back to top</button>

<script>
  const button = document.querySelector("#backToTop");

  button.addEventListener("click", () => {
    window.scrollTo({ top: 0, behavior: "auto" });
  });
</script>

Step by Step Execution

Consider this code:

const button = document.querySelector("#backToTop");

button.addEventListener("click", () => {
  window.scrollTo({ top: 0, behavior: "auto" });
});
  1. document.querySelector("#backToTop") finds the element whose id is backToTop.
  2. The returned button element is stored in button.
  3. addEventListener("click", ...) registers a function to run later, when the user clicks that button.
  4. A click occurs, so the arrow function runs.
  5. window.scrollTo(...) instructs the browser window to scroll.
  6. top: 0 sets the vertical scroll offset to the very beginning of the document.
  7. behavior: "auto" prevents JavaScript from requesting a smooth animation, so the position changes immediately under normal browser settings.

Real World Use Cases

  • Documentation pages: A back-to-top button helps readers navigate long API references.
  • Online stores: Users can quickly return to category filters after browsing many products.
  • Search results: After changing a search query or page of results, an application can place the user at the top of the new results.
  • Form validation: A form can scroll to the top when a summary of validation errors is displayed there.
  • Single-page applications: A client-side route change commonly resets the viewport so the next screen starts at its top.
Take Quiz

Real Codebase Usage

In production code, scrolling is usually triggered by a user action or a navigation event rather than run immediately when a script loads.

Show the button only after scrolling down

const button = document.querySelector("#backToTop");

window.addEventListener("scroll", () => {
  const hasScrolledDown = window.scrollY > 400;
  button.hidden = !hasScrolledDown;
});

button.addEventListener("click", () => {
  window.scrollTo({ top: 0, behavior: "auto" });
});

window.scrollY is the current vertical scroll position. Hiding the control near the top prevents unnecessary interface clutter.

Reset after a route or view change

function showSearchResults(results) {
  renderResults(results);
  window.scrollTo({ top: 0, behavior: "auto" });
}

Scroll after rendering or changing the view when the expected reading position should be the top.

Scroll a container instead of the whole page

Some layouts make a panel scrollable rather than the browser window:

const resultsPanel = document.querySelector(".results-panel");
resultsPanel.scrollTo({ top: 0, behavior: "auto" });

Use the element's scrollTo() method when that element, not the page, owns the scrollbar.

Common Mistakes

Scrolling the wrong thing

This scrolls the browser window:

window.scrollTo({ top: 0 });

If the visible scrollbar belongs to a nested element with overflow: auto or overflow: scroll, it will not move. Scroll that element instead:

const panel = document.querySelector(".scrollable-panel");
panel.scrollTo({ top: 0 });

Accidentally requesting smooth scrolling

window.scrollTo({ top: 0, behavior: "smooth" });

This animates the movement. Use "auto" when an immediate jump is required:

window.scrollTo({ top: 0, behavior: "auto" });

Running code before the button exists

This can fail if the script runs before the HTML button is parsed:

const button = document.querySelector("#backToTop");
button.addEventListener("click", scrollToTop);

Place the script near the end of <body>, use defer for an external script, or wait for DOMContentLoaded.

Forgetting that a link navigates

A back-to-top control made as <a href="#"> can alter the URL fragment or cause unwanted navigation behavior. A real action is better represented by a button:

<button type="button">Back to top</button>

Using outdated document scroll properties as the primary solution

You may find code such as this:

document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;

These properties are useful when maintaining legacy code, but window.scrollTo() is clearer and is the preferred modern API for scrolling the page.

Comparisons

ApproachBest useInstant by default?Notes
window.scrollTo({ top: 0 })Scroll the browser pageYes with autoClear, modern page-scrolling API.
window.scrollTo(0, 0)Short, simple page scrollYesPositional arguments are concise but less self-documenting.
element.scrollTo({ top: 0 })Scroll a nested containerYes with autoUse for panels, modals, and scrollable lists.
window.scrollBy(...)Move relative to current positionYes with autoscrollBy changes position by a distance; it does not target an absolute location.
element.scrollIntoView()Reveal a particular elementOftenUseful when an element, rather than the document coordinate 0, is the destination.

scrollTo uses an absolute destination. scrollBy uses a relative movement:

window.scrollTo({ top: 0 });      // Go exactly to the page top
window.scrollBy({ top: -300 });   // Move up 300 pixels from here
Take Quiz

Cheat Sheet

// Modern, explicit: immediately go to the page top
window.scrollTo({ top: 0, left: 0, behavior: "auto" });

// Short positional form
window.scrollTo(0, 0);

// Scroll a nested element to its top
const container = document.querySelector(".scrollable");
container.scrollTo({ top: 0, behavior: "auto" });

// Current vertical page offset
console.log(window.scrollY);
  • Use window.scrollTo() for the document viewport.
  • Use element.scrollTo() for an element with its own scrollbar.
  • top: 0 means the topmost vertical position.
  • behavior: "auto" requests normal, non-smooth scrolling.
  • scrollTo is absolute; scrollBy is relative.
  • Use a <button> for a Back to top action.

FAQ

How do I instantly scroll to the top in JavaScript?

Use:

window.scrollTo({ top: 0, behavior: "auto" });

Does window.scrollTo(0, 0) scroll instantly?

Yes. It sets the horizontal and vertical page offsets to zero without requesting a smooth animation.

Why does window.scrollTo() not move my visible scrollbar?

The scrollbar may belong to a nested scrollable element rather than the browser window. Select that element and call element.scrollTo({ top: 0 }).

What is the difference between scrollTo and scrollBy?

scrollTo moves to an exact coordinate. scrollBy moves by a distance relative to the current position.

Can I use CSS scroll-behavior: smooth and still make this instant?

Specify behavior: "auto" in the JavaScript call. If project styling or browser behavior produces an unexpected animation, check the page's CSS and test the intended browser environment.

Should a Back to top control be a link or a button?

Use a button when JavaScript performs the action. It accurately represents an action rather than navigation to a new resource.

Is document.body.scrollTop = 0 the recommended method?

No. It appears in older code, but window.scrollTo() is clearer and better suited to modern browser code.

Take Quiz

Mini Project

Description

Build an instant Back to top button for a long article. The button stays hidden while the reader is near the beginning of the page and appears after they scroll down. This is a common navigation convenience on documentation, blog, and catalog pages.

Goal

Create a button that appears after scrolling down 300 pixels and instantly returns the browser viewport to the top when clicked.

Requirements

  • Add enough page content for the document to scroll.
  • Add a button with the visible text Back to top.
  • Keep the button hidden while the page is near the top.
  • Show the button after the user scrolls more than 300 pixels down.
  • Scroll instantly to the top when the button is clicked.
Take Quiz

Keep learning

Related questions

View more