Created
August 8, 2022 16:40
-
-
Save waterrmalann/3351548fde5d52a919c95f4b81a061cd to your computer and use it in GitHub Desktop.
Yet another but wonky implementation of scroll based animations for web. For use with Animate.css.
This file contains 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
/* Scroll Attached Animations */ | |
// v1.0.0 (quite wonky) | |
// Written by Alan (github.com/waterrmalann) | |
// For use alongside: https://animate.style/ | |
// Never force your animations on the user. | |
// Don't animate if the user prefers reduced motion (browser accessibility setting). | |
const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; | |
if (!prefersReducedMotion) { | |
const elements = document.querySelectorAll('[data-animation]'); | |
const observer = new IntersectionObserver(handleIntersection); | |
elements.forEach(obs => { | |
// Observe all the animated elements. | |
observer.observe(obs); | |
// Initially set the elements to hidden visibility. | |
obs.style.visibility = "hidden"; | |
}); | |
function handleIntersection(entries, observer) { | |
entries.forEach(entry => { | |
// As soon as an animated element enters the view. | |
if (entry.intersectionRatio > 0) { | |
let _target = entry.target; | |
// Show it. | |
_target.style.visibility = "visible"; | |
// Attach the animation class(es) from data-animation | |
_target.className += " animate__animated " + _target.getAttribute('data-animation'); | |
// We no longer have to keep track of the element. | |
observer.unobserve(entry.target); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment