How to Smooth Scroll to an Element with Native Javascript

javascript
Published on April 20, 2019

Scrolling to an element can be achieved in Javascript using the scrollIntoView() method. Smooth animation and customizing the alignment can be set through the scrollIntoViewOptions parameter.

Quick Sample Code

// element which needs to be scrolled to
var element = document.querySelector("#post-container");

// scroll to element
element.scrollIntoView();

NOTE : The scrollIntoView method scrolls with respect to the scrollable parent of the element. In usual cases, this means the browser window. But in cases where the element is contained within another scrollable element (element having a scrollbar), scrolling happens with respect to the parent and not the browser window.

Customizing Scroll Behavior and Alignment with scrollIntoViewOptions Parameter

The scrollIntoView method also accepts a parameter through which you can set an animated scroll behavior and also customize its alignment.

This parameter scrollIntoViewOptions is an object with the following properties :

  • behavior : This sets whether scrolling should be an animated one or an instant scroll to the element. It can have the following values :

    • smooth : Does a smooth scrolling
    • auto : Instant scrolling. This is the default value.
  • block : This sets the vertical alignment of the shown element with respect to the scrollable parent. It can have the following values :

    • start : Element is aligned at the top of the scrollable parent. This is the default value.
    • center : Element is aligned at the middle of the scrollable parent.
    • end : Element is aligned at the bottom of the scrollable parent.
    • nearest : This aligns the element suited to the current situation. If user is currently above the element, it will be aligned at the bottom of the scrollable parent. If user is currently below the element, it will be aligned at the top. If is is already in view, nothing will happen.
  • inline : This sets the horizontal alignment of the shown element with respect to the scrollable parent. It can have the following values :

    • start : Element is aligned at the left of the scrollable parent.
    • center : Element is aligned at the middle of the scrollable parent.
    • end : Element is aligned at the right of the scrollable parent.
    • nearest : Aligns the element suited to the current situation. If user is currently at the right of the element, it will be aligned at the left of the scrollable parent. If user is currently at the left of the element, it will be aligned at the right. Nothing happens if already in view. This is the default value.
var element = document.querySelector("#post-container");

// smooth scroll to element and align it at the bottom
element.scrollIntoView({ behavior: 'smooth', block: 'end'});
In this Tutorial