code everywhere
technology, web services and applications

On scroll animations with Animate.css

posted on April 7, 2018, 8:08 pm in js, css

If you're looking to do CSS animations, you can't go wrong using this wonderful library at daneden.github.io/animate.css .

It has tons of options but, they all happen on page load. Here's a small JS snippet that will apply those animations when an element comes into view.

var init;
window.addEventListener('scroll', function(e) {
    
// why init? so we don't run animations when jumping to a page using #anchor tags
    
init = ( init == undefined ) ? document.getElementsByTagName('body')[0].getBoundingClientRect().top init;
console.log(initdocument.getElementsByTagName('body')[0].getBoundingClientRect().top);
    
// Get all the elements, must be in form "animatedOnScroll effect"
    
var elems document.getElementsByClassName('animatedOnScroll');
    for( var 
i=0i<elems.length && init > -20i++) {
        if( 
elems[i].getBoundingClientRect().top <= window.innerHeight ) {
            var 
classNameArray elems[i].className.split(' ');
            var 
atIndex classNameArray.indexOf('animatedOnScroll');
            var 
effect classNameArray[atIndex+1];
            
elems[i].className elems[i].className.replace('animatedOnScroll ' effect,'') + ' animated ' effect;
        }
    }
});

Using animatedOnScroll effectName class naming convention, it works by measuring the elements position, then modifying the className to animated effectName when it comes into view.

Demo

*
*
*
*
*
*
*
*
*
*
*

recent posts

< back