Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
a way to detect if a given element is on the visible area of the page
function isElementVisible(el, fullVisible) {
// efp - element from point
function efp(x, y) {
return window.document.elementFromPoint(x, y);
}
function getVWidth() {
return window.innerWidth || window.document.documentElement.clientWidth;
}
function getVHeight() {
return window.innerHeight || window.document.documentElement.clientHeight;
}
const rect = el.getBoundingClientRect();
const vWidth = getVWidth();
const vHeight = getVHeight();
// Return false if it's not in the viewport
if (
rect.right < 0 ||
rect.bottom < 0 ||
rect.left > vWidth ||
rect.top > vHeight
) {
return false;
}
const topLeft = el.contains(efp(rect.left, rect.top));
const topRight = el.contains(efp(rect.right, rect.top));
const bottomLeft = el.contains(efp(rect.left, rect.bottom));
const bottomRight = el.contains(efp(rect.right, rect.bottom));
return fullVisible
? (topLeft && bottomLeft) || (topRight && bottomRight)
: topLeft || topRight || bottomLeft || bottomRight;
}
function isElementFullVisible(el) {
return isElementVisible(el, true);
}
// TODO: define the TS code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.