Skip to content

Instantly share code, notes, and snippets.

@markmur
Created July 13, 2018 08:45
Show Gist options
  • Save markmur/4f652419182ba82d3855c5c68cc1715e to your computer and use it in GitHub Desktop.
Save markmur/4f652419182ba82d3855c5c68cc1715e to your computer and use it in GitHub Desktop.
Is Element In Viewport
/**
* 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