How To Scroll To Element In Nested Scrollable Element

JavaScript

13/09/2021


Scrolling to an element using JavaScript isn't that difficult, no matter how nested the scrollable area is. Let's take the following layout as an example:

Scrollable window with a scrollable element

Example Layout

To scroll to any element in a scrollable view, we need to:

  • Get the distance (in pixels) of the element itself from the top of its parent, and
  • Scroll the parent view by said distance

How does this translate into code? First, fetch the DOM element you wish to scroll to and get its offset position.

JAVASCRIPT
const elementInScrollableDiv = document.getElementById('some-id')
const positionFromTopOfScrollableDiv = elementInScrollableDiv.offsetTop

Then apply the value to the scrollable parent!

JAVASCRIPT
const scrollableDivElement = document.getElementById('scrollable-div-id')
scrollableDivElement.scrollTop = positionFromTopOfScrollableDiv

WRITTEN BY

Code and stuff