Skip to content

Instantly share code, notes, and snippets.

@prantlf
Last active September 2, 2018 00:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prantlf/71048a676216e09763e28d692fc4e7c5 to your computer and use it in GitHub Desktop.
Save prantlf/71048a676216e09763e28d692fc4e7c5 to your computer and use it in GitHub Desktop.
Check, that an element can be really seen in the browser window
// Checks, that the element is not only visible in DOM,
// but that it can be really seen either in the window,
// or only in the visible part of the windows (viewport).
// The centre of the element has to be seen, at least.
function canBeSeen (element, inViewPort) {
// Filter out hidden elements
if (element.offsetHeight === 0) {
return false
}
// Get extents of the viewport
const viewportLeft = window.scrollX
const viewportTop = window.scrollY
// Get the element location in the viewport
const { top, left, width, height } = element.getBoundingClientRect()
// Compute the centre of the element
const centreX = left + width / 2 + viewportLeft
const centreY = top + height / 2 + viewportTop
if (inViewPort) {
const viewportWidth = window.innerWidth
const viewportHeight = window.innerHeight
// Filter out elements outside the viewport
if (centreX < viewportLeft || centreX > viewportLeft + viewportWidth ||
centreY < viewportTop || centreY > viewportTop + viewportHeight) {
return false
}
}
// Inspect the document at the element's location
const documentX = centreX + viewportLeft
const documentY = centreY + viewportTop
const topmostElement = document.elementFromPoint(documentX, documentY)
// Filter out elements covered by other elements
return element === topmostElement
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment