Skip to content

Instantly share code, notes, and snippets.

@ryandejaegher
Last active April 8, 2020 19:48
Show Gist options
  • Select an option

  • Save ryandejaegher/0dcffbb670a1c4655afd7184e3f92e2b to your computer and use it in GitHub Desktop.

Select an option

Save ryandejaegher/0dcffbb670a1c4655afd7184e3f92e2b to your computer and use it in GitHub Desktop.
Demo of intersection observer inspired by Alligator.io
/*
Use this to easily add a fading effect to elements using IntersectionObserver,
intersectionObserver will "watch" for elements visibility on the page
*/
(function () {
myImgs = document.querySelectorAll('img');
observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0 && entry.isIntersecting === true) {
console.log('in the view');
console.log(entry)
entry.target.style.opacity = '1';
entry.target.style.transform = 'scale(1)';
entry.target.style.transition = 'all 1s ease';
} else {
console.log(entry)
entry.target.style.opacity = '0';
entry.target.style.transform = 'scale(1.2)';
entry.target.style.transition = 'all 1s ease';
console.log('out of view');
}
});
}, {rootMargin:'50px',threshold:0.2});
myImgs.forEach(image => {
observer.observe(image);
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment