Animate Site Sections on Scroll Behavior

Want some motion in your ocean? In a sea of content, simple animations can make for a pleasant break from the humdrum. Use this setup to create sections of a webpage that will slide up and fade into view. Let’s get started.

See a demo of what we’ll create.

We’ll need to setup some CSS, add an associated selector to our page element. We’ll use jQuery and a custom snippet of javascript that allows for the animation to happen when the user scrolls to that area of the webpage.

First, the CSS…

/*animation element*/
.animation-element {
  opacity: 0;
}

.animation-element.slide-up {
  opacity: 0;
  transition: all 500ms linear;
  transform: translate3d(0, 100px, 0);
}

.animation-element.slide-up.in-view {
  opacity: 1;
  transform: translate3d(0px, 0px, 0px);
}

Then comes the javascript, be sure to add this after you’ve included jQuery. Copying and pasting the below will do it.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>

<script>
var $animation_elements = $('.animation-element');
var $window = $(window);

function check_if_in_view() {
  var window_height = $window.height();
  var window_top_position = $window.scrollTop();
  var window_bottom_position = (window_top_position + window_height);
 
  $.each($animation_elements, function() {
    var $element = $(this);
    var element_height = $element.outerHeight();
    var element_top_position = $element.offset().top;
    var element_bottom_position = (element_top_position + element_height);
 
    //check to see if this current container is within viewport
    if ((element_bottom_position >= window_top_position) &&
        (element_top_position <= window_bottom_position)) {
      $element.addClass('in-view');
    } else {
      $element.removeClass('in-view');
    }
  });
}

$window.on('scroll resize', check_if_in_view);
$window.trigger('scroll');
</script>

Ok, now ensure your css classes are added to the desired elements. You should be good to go! Animate.

/* things we want to animate - can be added to more than one items */ 

<section class="animation-element slide-up">
/* things go here */
</section>

<aside class="animation-element slide-up">
/* also slides into view */ 
</aside> 

Following the above, your items should now animate – sliding up and from transparent into full opacity. Should you want to slide items from the left or right, this pen on animations should compliment all of what you’ve already found here. Happy animating!

Leave a Reply

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