Created
June 12, 2023 15:23
-
-
Save ahmu83/4cc93f9f990b048554db3fc0a7909a4b to your computer and use it in GitHub Desktop.
Check if an element is in the viewport using getBoundingClientRect method
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 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