0
0
JavascriptHow-ToBeginner · 3 min read

How to Scroll to Top in JavaScript: Simple Methods Explained

To scroll to the top in JavaScript, use window.scrollTo(0, 0) or window.scroll({ top: 0, behavior: 'smooth' }) for smooth scrolling. These commands move the page view to the top instantly or smoothly.
📐

Syntax

The main ways to scroll to the top are:

  • window.scrollTo(x, y): Scrolls instantly to the coordinates (x, y). Use window.scrollTo(0, 0) to go to the top-left corner.
  • window.scroll(options): Scrolls with options like smooth behavior. Example: window.scroll({ top: 0, behavior: 'smooth' }).
javascript
window.scrollTo(0, 0);

// or with smooth behavior
window.scroll({ top: 0, behavior: 'smooth' });
💻

Example

This example shows a button that scrolls the page to the top smoothly when clicked.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scroll to Top Example</title>
  <style>
    body {
      height: 2000px;
      padding: 20px;
      font-family: Arial, sans-serif;
    }
    button {
      position: fixed;
      bottom: 30px;
      right: 30px;
      padding: 10px 15px;
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <button id="scrollTopBtn">Scroll to Top</button>

  <script>
    const btn = document.getElementById('scrollTopBtn');
    btn.addEventListener('click', () => {
      window.scroll({ top: 0, behavior: 'smooth' });
    });
  </script>
</body>
</html>
Output
A webpage with a tall page and a button at bottom-right; clicking the button smoothly scrolls the page to the top.
⚠️

Common Pitfalls

Common mistakes include:

  • Using window.scrollTo without coordinates, which does nothing.
  • Expecting smooth scrolling without specifying behavior: 'smooth'.
  • Trying to scroll elements that are not scrollable or forgetting to target the right element.
javascript
/* Wrong: no coordinates */
window.scrollTo(); // Does nothing

/* Right: specify coordinates */
window.scrollTo(0, 0);

/* Wrong: smooth behavior missing */
window.scroll({ top: 0 }); // Instant scroll

/* Right: smooth scroll */
window.scroll({ top: 0, behavior: 'smooth' });
📊

Quick Reference

MethodDescriptionExample
window.scrollTo(x, y)Scroll instantly to coordinateswindow.scrollTo(0, 0)
window.scroll(options)Scroll with options like smooth behaviorwindow.scroll({ top: 0, behavior: 'smooth' })

Key Takeaways

Use window.scrollTo(0, 0) to jump instantly to the top of the page.
Use window.scroll({ top: 0, behavior: 'smooth' }) for smooth scrolling effect.
Always specify coordinates or options; calling scroll functions without them does nothing.
Make sure the page or element is scrollable to see the effect.
Attach scroll commands to events like button clicks for user interaction.