Skip to content

Instantly share code, notes, and snippets.

@netcall-jlo
Created August 8, 2023 07:50
Show Gist options
  • Save netcall-jlo/4f1951f69bbbd2e25559adc5d05b4c8c to your computer and use it in GitHub Desktop.
Save netcall-jlo/4f1951f69bbbd2e25559adc5d05b4c8c to your computer and use it in GitHub Desktop.
A function that takes an element and finds the parent element that scrolls. Useful in very specific circumstances
/**
* Takes an element and finds the parent element that would scroll.
*
* @param {Element} element
* Element whose scrolling parent should be returned.
* @return {Element|null}
* Parent element that scrolls. If no parent can be found, null is
* returned.
*/
function getScrollingParent(element) {
const parent = element?.parentElement;
switch (
parent &&
parent.nodeType === Node.ELEMENT_NODE &&
window.getComputedStyle(parent, null).getPropertyValue('overflow-y')
) {
case 'visible':
return getScrollingParent(parent);
case 'auto':
case 'scroll':
return parent;
default:
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment