Skip to content

Instantly share code, notes, and snippets.

@ahmu83
Created June 12, 2023 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmu83/4cc93f9f990b048554db3fc0a7909a4b to your computer and use it in GitHub Desktop.
Save ahmu83/4cc93f9f990b048554db3fc0a7909a4b to your computer and use it in GitHub Desktop.
Check if an element is in the viewport using getBoundingClientRect method
/**
* Check if an element is in the viewport using getBoundingClientRect method
*
* Copied from: https://www.30secondsofcode.org/js/s/element-is-visible-in-viewport/
*
* @param object el Element object
* @param boolean partiallyVisible If element is partially visible or not
* @return boolean
*/
function elementInViewport(el, partiallyVisible = true) {
if ( typeof jQuery === "function" && el instanceof jQuery ) {
el = el.get(0);
}
var { top, left, bottom, right } = el.getBoundingClientRect();
var { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) ||
(bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment