Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Last active May 6, 2019 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkobridee/6764f6f210b38b881133cfee61fbd3eb to your computer and use it in GitHub Desktop.
Save erkobridee/6764f6f210b38b881133cfee61fbd3eb to your computer and use it in GitHub Desktop.
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