Last active
May 28, 2024 18:30
-
-
Save BroFox86/9d4013ff18586b0458ddd4459b115bce to your computer and use it in GitHub Desktop.
[isInViewportArea] Check if element has reached specific viewport area #jsTrick
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 isInViewportArea( element ) { | |
const coords = getCoords( element ); | |
const viewportTop = pageYOffset; | |
const viewportBottom = pageYOffset + document.documentElement.clientHeight; | |
// If an element has appeared on the bottom. | |
if ( viewportBottom > coords.top ) { | |
return true; | |
} | |
// If an element has reached the top. | |
if ( viewportTop > coords.top ) { | |
return true; | |
} | |
// If an element has gone from the top. | |
if ( viewportTop > coords.bottom ) { | |
return true; | |
} | |
} | |
function getCoords( elem ) { | |
const box = elem.getBoundingClientRect(); | |
return { | |
top: box.top + pageYOffset, | |
bottom: box.bottom + pageYOffset, | |
left: box.left + pageXOffset, | |
right: box.right + pageXOffset | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment