Scroll to Specific Page Position in JavaScript

JavaScript gives you a simple way to scroll to any position on a web page using the window.scrollTo() method. This is useful for smooth navigation, auto-scrolling effects, or jumping to a specific section after clicking a button.

In this article, you’ll learn how to use scrollTo() and scrollIntoView() with examples for both instant and smooth scrolling.


 What is window.scrollTo()?

The window.scrollTo() method scrolls the browser window to a specific location on the page using X (horizontal) and Y (vertical) coordinates.

 Syntax:

    window.scrollTo(x, y);
  • x: Number of pixels to scroll horizontally

  • y: Number of pixels to scroll vertically


 Example: Scroll to Top of Page

    <button onclick="scrollToTop()">Go to Top</button>

    <script>
    function scrollToTop() {
    window.scrollTo(0, 0);
    }
    </script>

What it does:
When the button is clicked, the page scrolls back to the top instantly.


 Example: Scroll to a Specific Vertical Position

    <button onclick="scrollToPosition()">Scroll Down 500px</button>

    <script>
    function scrollToPosition() {
    window.scrollTo(0, 500); // Scrolls 500 pixels down from the top
    }
    </script>

 Smooth Scrolling Option

You can make the scroll smooth by using the behavior option:

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


 Scroll to an Element with scrollIntoView()

Instead of using exact pixel values, you can scroll directly to an element:

    <button onclick="scrollToSection()">Go to Section</button>

    <div style="margin-top: 1000px;" id="mySection">
    <h2>This is the target section</h2>
    </div>

    <script>
    function scrollToSection() {
    document.getElementById("mySection").scrollIntoView({ behavior: "smooth" });
    }
    </script>

What it does:
Scrolls smoothly to the element with the ID mySection.


 Common Use Cases

  • "Back to Top" buttons

  • Navigation links for long pages

  • Jumping to sections with buttons

  • Automatically scrolling to a form error


 Tips and Notes

  • Smooth scroll may not work in very old browsers (consider a polyfill if needed).

  • Always test scrolling behavior on both desktop and mobile for best user experience.

  • Avoid sudden jumps that may confuse users — prefer smooth scrolling when possible.


 Summary

JavaScript makes it easy to scroll to a specific position or element on the page. Whether you're jumping to a section or creating smooth scroll effects, scrollTo() and scrollIntoView() are powerful tools to enhance user experience.

 Key Takeaways:

  • Use window.scrollTo(x, y) to scroll by pixel position

  • Use scrollIntoView() to scroll to a specific element

  • Use { behavior: "smooth" } for a smooth effect

  • Ideal for navigation, UX enhancements, and auto-focus