Created
June 14, 2018 19:34
-
-
Save jeangontijo/9a7acf01c4b5f2283208d7d7cf7cb231 to your computer and use it in GitHub Desktop.
Change the class when the element is visible in the viewport
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
var visible = document.querySelectorAll('.element'); | |
function isInViewport(el) { | |
var rect = el.getBoundingClientRect(); | |
return ( | |
// when any part of element is visible | |
rect.top >= -el.clientHeight && | |
rect.left >= -el.clientWidth && | |
rect.bottom <= window.innerHeight + el.clientHeight && | |
rect.right <= window.innerWidth + el.clientWidth | |
// when 50% of the element is visible | |
// rect.top >= -el.clientHeight/2 && | |
// rect.left >= -el.clientWidth/2 && | |
// rect.bottom <= window.innerHeight + el.clientHeight/2 && | |
// rect.right <= window.innerWidth + el.clientWidth/2 | |
// when 100% of the element is visible | |
// rect.top >= 0 && | |
// rect.left >= 0 && | |
// rect.bottom <= window.innerHeight && | |
// rect.right <= window.innerWidth | |
); | |
} | |
window.addEventListener('scroll', function(e) { | |
visible.forEach(function(visible) { | |
if (isInViewport(visible) === true) { | |
visible.classList.add('visible'); | |
} | |
if (isInViewport(visible) === false) { | |
visible.classList.remove('visible'); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment