Running CSS animations when the element is shown

Not a unique idea at all, many existing libraries out there, but I wanted a very basic jQuery plugin that I controlled entirely with CSS animations and classes being applied when the user scrolled to (or past) the element, along with a few key features: chaining animations to run in sequence, customisable delays and customisable visibility offsets.

Some code snippets from the example page. The get started, all you need to add to your page is:

then you can add the following classes to your page and the animations will work when the user scrolls to them:

All delays are relative to the first element shown with a data-animate-chain attribute, so when this first element is shown, the timeouts are set up for all other elements with the same data-animate-chain attributes.

The CSS is pretty straightforward and some basic example animations are defined in animations.css

The simplified example above controls the basis for the plugin, first all elements with an animate-on-show class are set up with a 1s animation. Then the child classes, in this case fade-in are defined with an initial state, and how it should end once the animation is applied (.animated). The plugin essentially just applies the animated class to each element that is deemed visible and CSS does the rest. The additional chaining happens at the same time along with accounting for delays.

There are some global settings you can define, including vertical adjustments for some classes. For example slide-in-from-below:

is configured with an initial state of 400px below the target end location, this means we have to adjust our offset by 400. The $.AnimateOnShow.settings.custom object handles this:

If you’re adding in other animations that adjust the vertical position, be sure to add these to your version of the plugin or change in your page’s script via $.AnimateOnShow.settings.custom['your-classname-here'] = <adjustment>.

Hope this saves someone some time if they want to do something similar!

I’ve made it a fairly customisable package although it does currently rely on jQuery as the site for which this was originally developed already had it.

There’s a demo page that includes download links and you are free to use this code however you see fit!

Leave a Reply

Your email address will not be published. Required fields are marked *