Skip to content

Instantly share code, notes, and snippets.

@xkomiks
Last active September 10, 2021 13:48
Show Gist options
  • Save xkomiks/afc0362432187b3d2b000dcd436fbe83 to your computer and use it in GitHub Desktop.
Save xkomiks/afc0362432187b3d2b000dcd436fbe83 to your computer and use it in GitHub Desktop.
Return an array of elements that scroll horizontally or vertically
const canUseDOM = () => (
typeof window !== 'undefined' &&
typeof window.document !== 'undefined' &&
typeof window.document.createElement !== 'undefined'
);
function elementsWithScrolls() {
if (!canUseDOM()) {
return;
}
const getCss = (elem, style) => getComputedStyle(elem)[style];
const autoOrScroll = (text) => text === 'scroll' || text === 'auto';
const isXScrollable = (elem) => elem.offsetWidth < elem.scrollWidth && autoOrScroll(getCss(elem, 'overflow-x'));
const isYScrollable = (elem) => elem.offsetHeight < elem.scrollHeight && autoOrScroll(getCss(elem, 'overflow-y'));
const hasScroller = (elem) => isYScrollable(elem) || isXScrollable(elem);
return [...document.querySelectorAll('*')].filter(hasScroller);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment