Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Created August 29, 2016 15:43
Show Gist options
  • Save andreasvirkus/28b317aa9adff832b8e9ac732ae7c949 to your computer and use it in GitHub Desktop.
Save andreasvirkus/28b317aa9adff832b8e9ac732ae7c949 to your computer and use it in GitHub Desktop.
/**
* Credit goes to the very useful gomakethings.com
*
* https://gomakethings.com/ditching-jquery/
*
* Determine if an element is in the viewport
* @param {Node} elem The element
* @return {Boolean} Returns true if element is in the viewport
*/
var isInViewport = function ( elem ) {
var distance = elem.getBoundingClientRect();
return (
distance.top >= 0 &&
distance.left >= 0 &&
distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
distance.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
var elem = document.querySelector( '#some-element' );
isInViewport( elem ); // Boolean: returns true/false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment