JS Tip of the Day: Scrolling an Element into View

Scrolling an Element into View
Level: Beginner

Have you ever thought about automatically scrolling the user to a specific location in a web page, for example the location of some div or other element in the DOM? If so, you might have thought that to do so, you’d have to write a function that would need to make calculations based on the target element’s position, the current scroll position, and maybe even the height of the viewport depending on where in the page you’d want to scroll. Good news, everyone! It turns out that it’s much easier than all that. HTML elements have their very own, dedicated method for scrolling themselves into view, the aptly named scrollIntoView.

let scrollTarget = document.getElementById('my-element');
scrollTarget.scrollIntoView();

The above example will immediately scroll the element with the id ‘my-element’ into view. If you want the scroll to be smooth, that can also be specified (for browsers that support it).

// smooth scrolling may not be supported everywhere
let scrollTarget = document.getElementById('my-element');
scrollTarget.scrollIntoView({ behavior: 'smooth' });

Additional options are also available. See the MDN link for more on those.

More info: