Skip to content

Instantly share code, notes, and snippets.

@twxia
Created January 5, 2018 03:41
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save twxia/bb20843c495a49644be6ea3804c0d775 to your computer and use it in GitHub Desktop.
Save twxia/bb20843c495a49644be6ea3804c0d775 to your computer and use it in GitHub Desktop.
Get Scrollable Parent
function getScrollParent(node) {
const isElement = node instanceof HTMLElement;
const overflowY = isElement && window.getComputedStyle(node).overflowY;
const isScrollable = overflowY !== 'visible' && overflowY !== 'hidden';
if (!node) {
return null;
} else if (isScrollable && node.scrollHeight >= node.clientHeight) {
return node;
}
return getScrollParent(node.parentNode) || document.body;
}
export default getScrollParent;
@yohaneslumentut
Copy link

Thank you

@ben-x-dev
Copy link

In some scenarios, overflowY could be: visible !important or hidden !important
To fix that, you can use:
const isScrollable = !(overflowY.includes('hidden') || overflowY.includes('visible'));

@dagalti
Copy link

dagalti commented Mar 1, 2019

Thanks. I rewrite like this. works good for me.

function getScrollParent(node){
if(!node) return null;
else if (node.scrollTop>0) return node;
return getScrollParent(node.parentNode) || document.documentElement;
}

@henriqemalheiros
Copy link

henriqemalheiros commented Apr 26, 2019

Based on what @nbcp said, here's my take on it:

const REGEXP_SCROLL_PARENT = /^(visible|hidden)/

export const getScrollParent = el =>
  !(el instanceof HTMLElement) || typeof window.getComputedStyle !== 'function'
    ? null
    : el.scrollHeight >= el.clientHeight && !REGEXP_SCROLL_PARENT.test(window.getComputedStyle(el).overflowY || 'visible')
      ? el
      : getScrollParent(el.parentElement) || document.body

@TheGitPanda
Copy link

Thank you for sharing this beautiful code!

@mandalorian2049
Copy link

謝謝威廉老師~ 我們公司也在用XD 讚讚

@sbogdaniuk
Copy link

Sometimes scrolling element is not body, so document.scrollingElement works for me. Caniuse

return getScrollParent(node.parentNode) || document.scrollingElement || document.body;

@oscarmarina
Copy link

Hi everyone, a version supporting shadow dom

https://gist.github.com/oscarmarina/3a546cff4d106a49a5be417e238d9558

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment