Skip to content

Instantly share code, notes, and snippets.

@tsq
Forked from jjmu15/in_viewport.js
Created June 4, 2017 08: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 tsq/42b47aaf7a18dceaec3de9136051ff67 to your computer and use it in GitHub Desktop.
Save tsq/42b47aaf7a18dceaec3de9136051ff67 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
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)
);
}
The above function could be used by adding a “scroll” event listener to the window and then calling isInViewport().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment