Find first scrollable parent
This JavaScript function can be used for detecting the first parent element of a specified element that permits scrolling:
Call getScrollableParent(element)
, replacing element
with your targeted element, for it to traverse up to the DOM and return the first element that allows vertical scrolling. If no such parent exists, you will be gifted with null
.
Understanding the function
Let's dissect this function to better understand how it identifies the scrollable parent.
Detecting scroll with computed styles
The function checks the computed style overflow-y
of every parent until it finds one with a value of either 'auto' or 'scroll', indicating a vertical scroll. It leverages window.getComputedStyle(n)['overflow-y']
to fetch this data.
Moving up the DOM
The function ascends the DOM tree via node.parentElement
, switching to each parent element in succession. The process is likened to climbing a ladder where each rung is a parent situated higher in the DOM tree.
The body is the fallback
If it doesn't find an explicit scrollable parent, our trusty function defaults to document.body
. This is because, in some scenarios like fixed-position elements, document.body
acts as the scrollable container.
Elevating the solution with enhancements
Orientation aware solution
This extended solution is brilliant for responsive web designs, as they often change the scrollable element with orientation changes by re-adjusting the layout.
Here, the function is triggered whenever the window is resized—including when the orientation is switched from portrait to landscape or vice versa.
Overflow X and Y
Our solution considers only vertical (y-axis) scrolling. However, if you wish to include horizontal scrolling, modify the regular expression as follows:
Syntax refactoring
Refactoring the function for ES6 syntax makes it cleaner and more maintainable.
Was this article helpful?