4 Comments

Creating Scroll Animations with Waypoints and Animate.css, Part 2

This spring, I detailed how to use CSS and Waypoints.js to create animations that are triggered as a user scrolls down the page.

In this post, I’ll show you how to reverse those animations to hide the content as the user scrolls back up the page.

What You’ll Need

  • Waypoints: A JavaScript library that allows us to execute a function when we scroll to an element.
  • Animate.css: A CSS animation library that enables sophisticated animations through HTML classes.
  • jQuery: Although not a dependency of either Waypoints or Animate.css, jQuery allows us to easily trigger our animations.

How It Works

1. Go to the animation code.

Below is the final code we used to set up the original Waypoints animations. We’ll build on this code to create our reversed animations.

<div id="element-to-animate" class="animated">
  ...
</div>
$(document).ready(function(){
 
  // hide our element on page load
  $('#element-to-animate').css('opacity', 0);
 
  $('#element-to-animate').waypoint(function() {
      $('#element-to-animate').addClass('fadeInLeft');
  }, { offset: '50%' });
 
}

2. Identify scroll direction.

Our goal is to reveal the content when the user scrolls down and to hide it when the user scrolls up. In order to achieve this, we need to be able to identify which direction the user is scrolling. Fortunately, Waypoints provides the Handler Option, an easy way to determine the user’s scroll direction. All we need to do is pass the Waypoint function a 'direction' parameter:

$(document).ready(function(){
 
  $('#element-to-animate').waypoint(function(direction) {
 
    if (direction === 'down') {
      // user is scrolling down, reveal our content
    } else if (direction === 'up') {
      // user is scrolling up, hide our content
    }
 
  }, { offset: '50%' });
 
});

Simple enough, right?

3. Add your animations.

To put it all together, let’s add our animations:

<div id="element-to-animate" class="animated">
  ...
</div>
$(document).ready(function(){
 
  // hide our element on page load
  $('#element-to-animate').css('opacity', 0);
 
  $('#element-to-animate').waypoint(function(direction) {
    if (direction === 'down') {
      // reveal our content
      $('#element-to-animate').addClass('fadeInLeft');
      $('#element-to-animate').removeClass('fadeOutLeft');
    } else if (direction === 'up') {
      // hide our content
      $('#element-to-animate').addClass('fadeOutLeft');
      $('#element-to-animate').removeClass('fadeInLeft');
    }
 
  }, { offset: '50%' });
 
});

Scroll down (now you see it) and up (now you don’t). Exactly the results we wanted.