Scroll Into View If Needed

Mahak Narayan Singh
2 min readSep 19, 2020

--

Problem Statement
Say you have an accordion with list of items that expands and collapses. What if on expanding an accordion item, the item goes outside the viewport. We need a way to auto scroll the page to the top or bottom so that the expanded accordion item is visible in the viewport. If on expanding, the element is already inside the viewport, we don’t need to do anything.

Solution
We can use combination of getBoundingClientRect and scrollIntoView Web API which are supported on all major browsers.

scrollIntoView()
The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user.

getBoudingClientRect()
The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

To check whether the expanded item is inside or outside the viewport, we can use getBoundingClientRect method and then call scrollIntoView method.

In order to check if the expanded item is outside the viewport from the bottom, we can use the following line of code:

target.getBoundingClientRect().bottom > window.innerHeight

In the same way, the following line of code can be used to know if the expanded item is outside the viewport from the top:

target.getBoundingClientRect().top < 0

Compiling all these into a single function:

--

--

No responses yet