Skip to content

Instantly share code, notes, and snippets.

@jeangontijo
Created June 14, 2018 19:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeangontijo/9a7acf01c4b5f2283208d7d7cf7cb231 to your computer and use it in GitHub Desktop.
Save jeangontijo/9a7acf01c4b5f2283208d7d7cf7cb231 to your computer and use it in GitHub Desktop.
Change the class when the element is visible in the viewport
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