-
-
Save thmsbkkr/5a3a66860fb12ddf0d38c57e292b41e4 to your computer and use it in GitHub Desktop.
check if element is in viewport - vanilla JS. Use by adding a “scroll” event listener to the window and then calling isInViewport().
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
// Determine if an element is in the visible viewport | |
export default function isInViewport(element) { | |
var rect = element.getBoundingClientRect(); | |
var html = document.documentElement; | |
return ( | |
rect.top >= 0 && | |
rect.left >= 0 && | |
rect.bottom <= (window.innerHeight || html.clientHeight) && | |
rect.right <= (window.innerWidth || html.clientWidth) | |
); | |
} | |
// | |
// Example on how you can use it. | |
// | |
import isInViewport from './functions/isInViewport'; | |
window.onscroll = function() { | |
let element = document.getElementById('your-id'); | |
if (isInViewport(element)) { | |
// Do something | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment