-
MDN web docs
-
[GitHub] thebuilder / react-intersection-observer - React component that monitors when an element enters or leaves the browser viewport. (with typescript support)
Last active
May 6, 2019 06:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// TODO: define the TS code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment