Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
window.scrollTo({ top: 0, behavior: "smooth" });
console.log(window.scrollY);

Try it

Scroll controls and live position
A reading-progress bar

Syntax

JavaScript
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.
  • scrollY can 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, check prefers-reduced-motion with matchMedia() and use "instant" or "auto" instead.
  • CSS can do it too. html { scroll-behavior: smooth; } makes in-page links and scrollTo() calls with "auto" animate.
  • Scroll events fire a lot. Keep handlers cheap, mark them { passive: true }, or use IntersectionObserver for "has this entered the viewport" checks.
  • Elements scroll too. element.scrollTo() and element.scrollTop work the same way for scrollable containers.
  • Restoring position. Browsers restore scroll on back navigation; change history.scrollRestoration only if you handle it yourself.
  • document.scrollingElement is the element that actually scrolls the page, and its scrollHeight gives 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.