Created
July 13, 2018 08:45
-
-
Save markmur/4f652419182ba82d3855c5c68cc1715e to your computer and use it in GitHub Desktop.
Is Element In Viewport
This file contains hidden or 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
/** | |
* Check if an element is within the viewport or considered visible | |
* @param {Object} bounds { top, left, bottom, right } - distances from container | |
* @param {Object} container - container object with { width, height } | |
* @return {Boolean} returns visibility state | |
*/ | |
const isInViewport = ({ top, left, bottom, right }, container) { | |
const isTallerThanViewport = top <= 0 && bottom >= container.height | |
const isWiderThanViewport = right >= container.width && left <= 0 | |
const withinXAxis = left >= 0 && right <= container.width | |
const withinYAxis = top >= 0 && bottom <= container.height | |
return ( | |
(isTallerThanViewport && withinXAxis) || | |
(isWiderThanViewport && withinYAxis) || | |
(withinXAxis && withinYAxis) | |
) | |
} | |
const element = document.getElementById('element').getBoundingClientRect() | |
const container = { | |
height: window.innerHeight || document.documentElement.clientHeight, | |
width: window.innerWidth || document.documentElement.clientWidth | |
} | |
isInViewport(element, container) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment