Scroll Into View If Needed
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()
TheElement
interface'sscrollIntoView()
method scrolls the element's parent container such that the element on whichscrollIntoView()
is called is visible to the user.getBoudingClientRect()
TheElement.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: