Skip to content

Instantly share code, notes, and snippets.

@Farmatique
Last active May 4, 2020 14:54
Show Gist options
  • Save Farmatique/c5d568991a123e0a267410f30c1462a9 to your computer and use it in GitHub Desktop.
Save Farmatique/c5d568991a123e0a267410f30c1462a9 to your computer and use it in GitHub Desktop.
Check if element is in viewport check if scrolled to element
//from here https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/
//NOTE: This script return true when ALL element is in the viewport, not only its part
var isInViewport = function (elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
if(isInViewport(document.querySelectorAll(".element")[0])){
//do something when element in viewport
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment