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:
-
x
: Number of pixels to scroll horizontally -
y
: Number of pixels to scroll vertically
Example: Scroll to Top of Page
What it does:
When the button is clicked, the page scrolls back to the top instantly.
Example: Scroll to a Specific Vertical Position
Smooth Scrolling Option
You can make the scroll smooth by using the behavior
option:
Scroll to an Element with scrollIntoView()
Instead of using exact pixel values, you can scroll directly to an element:
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