Last active
October 5, 2018 10:17
-
-
Save luke-rmaki/1149b3d2496f7c34da80b7ee9bd7a368 to your computer and use it in GitHub Desktop.
Function to see if element is in 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
| function elementInView(target) { | |
| // selects target div | |
| const targetDiv = document.querySelector(target); | |
| // gets target position from top of viewport | |
| const targetPosition = targetDiv.getBoundingClientRect(); | |
| switch (true) { | |
| case targetPosition.top > 1: | |
| console.log('hidden'); | |
| break; | |
| case targetPosition.top <= 0 && targetPosition.bottom >= 0: | |
| console.log('visible'); | |
| break; | |
| case targetPosition.bottom < 0: | |
| console.log('hidden'); | |
| break; | |
| default: | |
| break; | |
| } | |
| } | |
| // add function to document.addEventListener('scroll') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment