.scrollTo()

atidua's avatar
Published Feb 26, 2025
Contribute to Docs

In JavaScript, .scrollTo() scrolls the window or document to a specified position in pixels.

Syntax

window.scrollTo(x, y)
  • x: The horizontal coordinate (in pixels) to scroll to.
  • y: The vertical coordinate (in pixels) to scroll to.

Or, alternatively:

window.scrollTo(options)
  • options: An object with the following optional properties:
    • left: The horizontal scroll position in pixels.
    • top: The vertical scroll position in pixels.
    • behavior: Defines the scrolling behavior. Accepted values:
      • smooth: Scrolls with an animation.
      • instant: Scrolls immediately.
      • auto: Uses the browser’s default scrolling behavior.

Example 1

The code below scrolls the window to 298 pixels from the left (x-axis) and 57 pixels from the top (y-axis) using absolute coordinates:

window.scrollTo(298, 57);

Example 2

The code below scrolls the window smoothly to 57 pixels from the top (y-axis) and 298 pixels from the left (x-axis) using the options object:

window.scrollTo({
top: 57,
left: 298,
behavior: 'smooth',
});

All contributors

Contribute to Docs

Learn JavaScript on Codecademy