Created
November 15, 2020 13:29
-
-
Save AitorAlejandro/958b984464bf8f978d7450949140ec40 to your computer and use it in GitHub Desktop.
How to check if the element specified is visible in the 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
| const elementIsVisibleInViewport = (el, partiallyVisible = false) => { | |
| const { top, left, bottom, right } = el.getBoundingClientRect(); | |
| const { 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; | |
| }; | |
| // Examples | |
| elementIsVisibleInViewport(el); // (not fully visible) | |
| elementIsVisibleInViewport(el, true); // (partially visible) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment