How to Use scrollIntoView Smooth Scrolling in JS

This article provides an overview of how the native JavaScript scrollIntoView() method handles programmatic smooth scrolling to specific DOM elements. It covers the core syntax, parameter options such as behavior, block, and inline, how the browser executes the animation under the hood, and essential considerations for accessibility and layout design.

The Basic Syntax for Smooth Scrolling

The Element.scrollIntoView() method scrolls the element’s ancestor containers so that the element on which it is called becomes visible to the user. To enable animated scrolling instead of an instant jump, pass an options object containing behavior: 'smooth':

const targetElement = document.getElementById("target-section");

targetElement.scrollIntoView({
  behavior: "smooth"
});

By default, omitting the options or passing behavior: 'auto' results in an immediate visual jump directly to the target element.

Customizing Alignment with Block and Inline Options

The options object allows precise control over where the target element settles within the visible viewport using the block (vertical) and inline (horizontal) properties.

targetElement.scrollIntoView({
  behavior: "smooth",
  block: "center",
  inline: "nearest"
});

How the Browser Executes Smooth Scrolling

When behavior: 'smooth' is invoked:

  1. Calculates Coordinates: The browser computes the starting scroll offset of the scroll container and the exact target coordinates based on the element’s bounding box and alignment options.
  2. Native Animation Loop: The browser handles the timing, frame rate, and easing curves natively via its internal rendering engine. This provides smoother, GPU-optimized rendering compared to manual animations using requestAnimationFrame or setInterval.
  3. Interrupt Handling: If the user scrolls manually or another programmatic scroll triggers while the animation is active, the browser naturally interrupts the ongoing smooth scroll and respects the new input.

Important Considerations

const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

targetElement.scrollIntoView({
  behavior: prefersReducedMotion ? "auto" : "smooth",
  block: "start"
});