Display CSS Animations When In Browser Viewport

CSS Animations can be easily applied to elements in HTML and viewed in the browser, but when the animation is lower down on the page it may have animated already before the user has scrolled to it.

Here's where Waypoints can solve the problem. (This example is done using WordPress). Waypoints allows you to run a script when it reaches an element on the page.

Set Up Javascript and Waypoints

Download the latest waypoints and link to the jquery.waypoints.min.js and set up a Javascript firing script.

<?php
add_action( 'wp_enqueue_scripts', 'prefix_in_browser' );
/**
* Enqueuing Waypoints & CSS Animate
*
*/
function prefix_in_browser() {
wp_enqueue_script( 'waypoints-init', get_stylesheet_directory_uri() . '/js/waypoints.init.js', array( 'waypoints' ), '1.0.0', true );
wp_enqueue_script( 'waypoints', get_stylesheet_directory_uri() . '/js/jquery.waypoints.min.js', array( 'jquery' ), '4.0.1', true );
wp_enqueue_style( 'animate-css', get_stylesheet_directory_uri() . '/css/animate.min.css', '3.7.0', 'all');
}

So the waypoints fire script and waypoints as well as the Animate.CSS file are all loaded.

Fire Up Waypoints

jQuery(document).ready(function($) {
$('#selector').waypoint(function() { // Add in your CSS selector
$('#selector').addClass("animated jello") ; // Change your CSS selector and use addClass to add 'animated' and the CSS Animation name
}, {
offset: '80%' // Change % for animation to start from distance to top of browser when element comes into the viewport
});
});
view raw waypoints-init.js hosted with ❤ by GitHub

The firing script adds the waypoint to the CSS selector used and then a function is called from that, that applies the two needed classes to fire the animated CSS. Finally, the offset amount determines when to start the animation by the percentage the element is from the top of the browser when the page is scrolled.

Leave a Comment