Skip to content

Instantly share code, notes, and snippets.

@dorkitude
Forked from michelbio/in_viewport.js
Created December 19, 2016 22:49
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 dorkitude/f0752a99fc810cb1d6c3bd367a9fa1c1 to your computer and use it in GitHub Desktop.
Save dorkitude/f0752a99fc810cb1d6c3bd367a9fa1c1 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().
// Determine if an element is in the visible viewport
// The function could be used by adding a “scroll” event listener to the window and then calling isInViewport().
function isInViewport(element) {
let rect = element.getBoundingClientRect();
let html = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight) &&
rect.right <= (window.innerWidth || html.clientWidth)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment