Skip to content

Instantly share code, notes, and snippets.

@BroFox86
Last active May 28, 2024 18:30
Show Gist options
  • Save BroFox86/9d4013ff18586b0458ddd4459b115bce to your computer and use it in GitHub Desktop.
Save BroFox86/9d4013ff18586b0458ddd4459b115bce to your computer and use it in GitHub Desktop.
[isInViewportArea] Check if element has reached specific viewport area #jsTrick
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