JavaScript Reference ยท Browser and Web APIs
window.scrollTo() and scroll position
Reference for window.scrollTo(), scrollBy(), scrollX and scrollY: read the scroll position, scroll smoothly, and build a reading-progress indicator.
The window exposes the page's scroll position through two read-only numbers, scrollX and scrollY, and scrolls it with scrollTo() (absolute position) and scrollBy() (relative movement). Both methods accept either two numbers or an options object, and the options form can ask for smooth animation.
To scroll a particular element into view instead of using coordinates, see scrollIntoView(). To react to scrolling, listen for the scroll event.
window.scrollTo({ top: 0, behavior: "smooth" }); console.log(window.scrollY);
Try it
Syntax
window.scrollTo(x, y) window.scrollTo(options) window.scrollBy(dx, dy) window.scrollBy(options) window.scrollX // also pageXOffset window.scrollY // also pageYOffset
| Name | Description |
|---|---|
x, y |
Target position in CSS pixels, measured from the top left of the document. |
dx, dy |
Distance to move from the current position. Negative values scroll up or left. |
options.top, options.left |
Same as y and x (or dy and dx for scrollBy()). |
options.behavior |
"auto" (default, follows CSS scroll-behavior), "smooth", or "instant". |
Return value: undefined. window.scroll() is an alias of scrollTo().
Usage notes
- Coordinates are clamped. Asking for a position beyond the document just scrolls as far as possible, so
scrollTo(0, 1e9)reaches the bottom. scrollYcan be fractional on high-density or zoomed displays. Round it before showing it to users.behavior: "smooth"is an animation, so for people who ask for less motion, checkprefers-reduced-motionwithmatchMedia()and use"instant"or"auto"instead.- CSS can do it too.
html { scroll-behavior: smooth; }makes in-page links andscrollTo()calls with"auto"animate. - Scroll events fire a lot. Keep handlers cheap, mark them
{ passive: true }, or useIntersectionObserverfor "has this entered the viewport" checks. - Elements scroll too.
element.scrollTo()andelement.scrollTopwork the same way for scrollable containers. - Restoring position. Browsers restore scroll on back navigation; change
history.scrollRestorationonly if you handle it yourself. document.scrollingElementis the element that actually scrolls the page, and itsscrollHeightgives the full document height.
Browser support
scrollTo(), scrollBy(), scrollX and scrollY work in every browser. The options object and behavior: "smooth" are supported in all current browsers; the "instant" value is newer, so check a compatibility table.