Skip to content

Instantly share code, notes, and snippets.

@mariusbolik
Created November 11, 2022 10:18
Show Gist options
  • Save mariusbolik/119b1cd571c2b901e466a12b203fedfe to your computer and use it in GitHub Desktop.
Save mariusbolik/119b1cd571c2b901e466a12b203fedfe to your computer and use it in GitHub Desktop.
Check if HTML Element is visible in Viewport
isVisible(elem: HTMLElement) {
if (!(elem instanceof Element)) { throw Error('DomUtil: elem is not an element.'); }
const style = getComputedStyle(elem);
if (style.display === 'none') { return false; }
if (style.visibility !== 'visible') { return false; }
if (Number(style.opacity) < 0.1) { return false; }
if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
elem.getBoundingClientRect().width === 0) {
return false;
}
const elemCenter = {
x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
};
if (elemCenter.x < 0) { return false; }
if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) { return false; }
if (elemCenter.y < 0) { return false; }
if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) { return false; }
const pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y) as HTMLElement;
do {
if (pointContainer === elem) { return true; }
} while (pointContainer === pointContainer.parentNode);
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment