Animate on Scroll Using CSS3 Animations And Intersection Observer

Category: Animation , Javascript | March 28, 2022
Author:Geoff Dusome
Views Total:936 views
Official Page:Go to website
Last Update:March 28, 2022
License:MIT

Preview:

Animate on Scroll Using CSS3 Animations And Intersection Observer

Description:

Have you ever wanted to add a cool animation on page scroll effects for your website? It is one of the top trends in web development and design.

Today I’ll be sharing you with a dead-simple way to use the Intersection Observer API to trigger CSS3 animations on scroll by calling a function when scrolling meets a given height threshold. Let’s get started.

See It In Action:

How to use it:

1. Add the CSS class ‘is-animated’ to the target elements.

<div class="is-animated">
  <h2>Animate On Scroll</h2>
</div>
<div class="is-animated">
  <h2>Animate On Scroll</h2>
</div>
<div class="is-animated">
  <h2>Animate On Scroll</h2>
</div>
...

2. Apply CSS3 animations to the elements when they’re scrolled into view.

.is-animated {
  opacity: 0;
  transform: translateY(35%);
  transition: opacity 0.7s, transform 0.7s;
}
.is-animated.scrolled-into-view {
  opacity: 1;
  transform: translateY(0);
  transition: opacity 0.7s, transform 0.7s;
}

3. The main CSS to detect if the elements are visible while scrolling down. If yes, apply the ‘.scrolled-into-view’ class to those elements.

// create our new observer, we want the trigger point of elements to be when the element is 25% visible.
// you could create multiple observers with different thresholds if necessary
let observer = new IntersectionObserver( isElScrolledIntoView, {
    root: null,
    rootMargin: '0px',
    threshold: 0.25
});
// grab our elements, this will be a global class for animating elements
const elements = document.querySelectorAll('.is-animated');
// loop over all elements and observe each of them
elements.forEach( element => {
  observer.observe(element);
});
// create our "what to do with each observed element" function
function isElScrolledIntoView( entries ) {
  // again loop over all entries (element)
  entries.forEach( entry => {
    // check if the entry is intersecting at our set threshold
    if ( entry.isIntersecting ) {
      // set a class to toggle animation
      entry.target.classList.add('scrolled-into-view');
      // if we only want to play the animation once per page, let's also add a class for that
      entry.target.classList.add('scrolled-into-view-first-time');
    } else {
      // if we've stopped intersecting, let's remove the animation
      entry.target.classList.remove('scrolled-into-view');
    }
  });
}

You Might Be Interested In:


Leave a Reply