Created
May 9, 2019 19:35
-
-
Save barkdoll/44987e9159f642883d709bc9b91921b3 to your computer and use it in GitHub Desktop.
Check if an element is [at least partially] in the browser viewport.
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
const onScreen = elm => { | |
const getViewportY = () => { | |
const top = window.pageYOffset || document.documentElement.scrollTop; | |
const bottom = top + document.documentElement.clientHeight; | |
return { top, bottom } | |
} | |
const getElmCoordinates = elm => { | |
const { top, bottom } = elm.getBoundingClientRect(); | |
return { top, bottom } | |
} | |
const viewport = getViewportY(); | |
const elmPosition = getElmCoordinates(elm); | |
const top = elmPosition.top + viewport.top; | |
const bottom = elmPosition.bottom + viewport.top; | |
const onScreenFlags = [ | |
(top >= viewport.top && top <= viewport.bottom), | |
(bottom >= viewport.top && bottom <= viewport.bottom) | |
]; | |
const atLeastPartlyOnScreen = onScreenFlags.includes(true); | |
return atLeastPartlyOnScreen; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment