Hi there, I was also looking for some magic script that can do this. I found some examples through google search and StackOverflow and tried to make a generic simple solution that can handle any number of elements animation on load and scroll.
You just have to create two CSS states for your elements, i.e. before the animation and during the animation. You need to add a class “animateOnView” to your element so that the script can detect the elements to animate on page load and scroll while appearing in the viewport. Just create the animation with the element’s class as a selector with “.animate”.
Add the script below after at the end of your HTML code i.e. just before closing </body> tag.
<script>
/* add a class to an element on viewport on pageload and scroll */
const signature = document.querySelectorAll(".animateOnView");
const animateElement = function(e){
let clientHeight = document.documentElement.clientHeight;
let signatureY = e.getBoundingClientRect().y;
let signatureH = e.getBoundingClientRect().height;
if (clientHeight > signatureY + (signatureH * 2) / 3 && !e.classList.contains("animate")) {
e.classList.add("animate");
}
}
signature.forEach(element => {
animateElement(element);
});
document.addEventListener("scroll", function () {
signature.forEach(element => {
animateElement(element);
});
});
</script>
With the following script added to the page. You will see the class “animate” gets added to the elements on page loads and scroll and the related CSS animation gets triggered.
Demo
See the Pen Untitled by Puneet Sharma (@webdevpuneet) on CodePen.