banner



How To Trigger Css Animation On Scroll

How to trigger a CSS animation on curl

by Nick Ciliak on

This is a step-by-step tutorial for how to create a CSS animation and trigger information technology on scroll using the Intersection Observer API. If you're new to Intersection Observer, don't let it scare you: it's like a fancy event listener, and information technology comes together in a few lines of code.

Triggering a CSS animation on coil is a type of whorl-triggered blitheness. When people say "on scroll", what they usually hateful is "when the chemical element is scrolled into view". This tutorial will encompass creating a CSS animation from scratch and applying it when the chemical element has been scrolled into view.

Define a CSS animation using keyframes

Let'southward start by creating a CSS animation. CSS animations are defined by keyframes.

                                          @keyframes                wipe-enter              {              
0% {
transform : calibration (0, .025) ;
}
l% {
transform : scale (1, .025) ;
}
}

Yous can name your animation anything you want. I've defined an animation where the element volition grow broad and and so tall.

Once your keyframes are defined, yous can use the animation on an chemical element by setting the blitheness-proper noun property to the name of your keyframes. You'll besides need to gear up an animation-duration to specify how long the animation should be and an blitheness-iteration-count to specify how many times the animation should play.

                                          @media                (                prefers-reduced-motion                :                no-preference)                            {              
.square {
blitheness-name : wipe-enter;
animation-duration : 1s;
animation-iteration-count : infinite;
}
}

I've wrapped the class in the prefers-reduced-motion: no-preference media query. This makes sure that our animation only runs if the user has not enabled the "reduce motility" setting on their operating organization.

For this demo, I've created a square element that will be animated. Here's what it looks like:

Yous tin also gear up upwards your CSS blitheness using a single autograph animation property like this:

                                          @media                (                prefers-reduced-movement                :                no-preference)                            {              
.square {
animation : wipe-enter 1s infinite;
}
}

Control the CSS animation with a class

Nosotros don't want the animation to play correct away. Nosotros tin can control when the animation is played by adding the blitheness properties to a separate class than the class used to style the element.

                          .square              {              
width : 200px;
height : 200px;
background : orange;
// etc...
}

@media ( prefers-reduced-motion : no-preference) {
.foursquare-blitheness {
animation : wipe-enter 1s 1;
}
}

When nosotros add together the animation class to the foursquare, the animation volition play. Attempt it:

You'll discover that the animation doesn't play every fourth dimension you click the button. That'south because the CSS blitheness will only trigger when the foursquare-animation class is added, not removed.

Even though the animation shows the element entering, the element is visible before the blitheness class is added. When the page first loads, we desire the element to be visible for the user even if the JavaScript is blocked or fails.

Add the class when the element is scrolled into view

We've created a CSS animation and can trigger information technology by adding the course to our element. Instead of adding and removing the grade when a push is clicked, we can add it when the element is scrolled into view.

There are three means to determine when the chemical element is scrolled into view:

  1. Use the Intersection Observer API
  2. Measure out the element's kickoff when the user scrolls
  3. Use a third-party JavaScript library that implements #1 or #2

For a basic scroll-triggered animation like the ane we are creating, I recommend using the Intersection Observer API because it requires less lawmaking and is better for performance.

The Intersection Observer API lets you continue runway of when one chemical element intersects with an some other and tells you when that happens. That'due south perfect for triggering a CSS animation on scroll. We want to know when our square intersects with the viewport. If information technology is intersecting, that means the square is in view and we should trigger our blitheness.

If you're familiar with event listeners in JavaScript, y'all tin can think of Intersection Observer as a fancy outcome listener with some extra options. Instead of attaching an effect listener to an chemical element, we tell the observer to continue rails of the chemical element and where it is on the folio.

Let's beginning by creating an observer and accept information technology keep rail of our square:

                          // Create the observer              
const observer = new IntersectionObserver ( entries => {
// We will fill in the callback later...
} ) ;

// Tell the observer which elements to rails
observer. detect (document. querySelector ( '.square' ) ) ;

By default, the root element that will be checked for intersection is the browser viewport, and so nosotros only need to tell the observer almost our foursquare.

When the callback function runs, it gives us an entries array of the target elements we asked it to watch, plus some boosted information about them. It will ever mitt back an array, even if y'all simply observe one element like we are here.

In the callback, we can loop over the array of entries to specify what we want to do. Each entry has an isIntersecting property that volition be true or false. If information technology's truthful, that means the element is visible within the viewport.

            entries.              forEach              (              entry              =>              {              
if (entry.isIntersecting) {
// Information technology's visible. Add the blitheness grade here!
}
} ) ;

Let'due south put it all together. Annotation that entry is the object given to united states of america by the observer and entry.target is the bodily element that we are observing, so that'southward where we should use the form.

                          const              observer              =              new              IntersectionObserver              (              entries              =>              {              
// Loop over the entries
entries. forEach ( entry => {
// If the chemical element is visible
if (entry.isIntersecting) {
// Add the animation class
entry.target.classList. add together ( 'square-animation' ) ;
}
} ) ;
} ) ;

observer. observe (document. querySelector ( '.square' ) ) ;

Now when the square is intersecting with the viewport, the blitheness class will be added, which volition play the animation.

If you want the animation to play every time the chemical element enters the viewport, yous need to remove the animation class when the element is no longer intersecting.

If the element you are animating changes size or position, it can exist catchy for the browser to decide if the element is currently in or out of the viewport. It's best to wrap the element you lot want to animate in an element that won't modify size or position and use that i for your observer instead of the element you are animating.

                                                            <div                class                                  =                  "square-wrapper"                                >                            
<div class = "square" > </div >
</div >

Then we observe the square-wrapper element and use the class to the foursquare like we did previously. If the wrapper is not intersecting, we can remove the class from the foursquare so that the animation volition restart next time it is scrolled into view.

                          const              observer              =              new              IntersectionObserver              (              entries              =>              {              
entries. forEach ( entry => {
const square = entry.target. querySelector ( '.square' ) ;

if (entry.isIntersecting) {
square.classList. add together ( 'square-blitheness' ) ;
return ; // if we added the form, exit the function
}

// Nosotros're not intersecting, so remove the grade!
square.classList. remove ( 'square-animation' ) ;
} ) ;
} ) ;

observer. observe (document. querySelector ( '.square-wrapper' ) ) ;

At present the square will breathing every time the wrapper chemical element enters the viewport. I've fabricated the wrapper element visible by giving information technology a dashed border. Effort scrolling upward and down over the demo below.

Success! By calculation and removing a CSS class when the element enters and leaves the viewport, we've successfully triggered a CSS animation on curl.

The Scroll Animation Handbook

8 ready-made gyre animations that will strengthen your site's message

Cheque it out

Trigger a CSS transition on scroll

If your animation simply has ane footstep, such every bit fading an element's opacity from 0 to 1, you lot can utilize a CSS transition instead of a CSS animation.

The method is essentially the same. Instead of defining keyframes for our animation form, we define the properties we desire to transition.

                          .square              {              
width : 200px;
tiptop : 200px;
background : teal;
border-radius : 8px;
opacity : 0;
transform : scale (one.2) ;
}

@media ( prefers-reduced-movement : no-preference) {
.square {
transition : opacity 1.5s ease, transform 1.5s ease;
}
}

.square-transition {
opacity : i;
transform : none;
}

Let'due south take some other square and accept it fade in when it enters the viewport. Yous can run across I've already added the foursquare-transition form to the HTML. That's because if the user has JavaScript blocked or information technology fails to load, they should encounter the element in its concluding transitioned state.

                                                            <div                class                                  =                  "square-wrapper"                                >                            
<div class = "square square-transition" > </div >
</div >

This is specially important since we are starting from opacity: 0. If we didn't have the square-transition course setup and the JavaScript fails, the user wouldn't come across the element at all! If your transition is to make something fade out, you lot probably wouldn't want to do this.

When the JavaScript first runs, we can remove the grade and then information technology can be added dorsum when nosotros actually want the transition to occur. This should be done outside of the observer, preferably at the start of your JavaScript. Hither's the full lawmaking:

                          // Remove the transition grade              
const foursquare = document. querySelector ( '.square' ) ;
foursquare.classList. remove ( 'square-transition' ) ;

// Create the observer, same every bit before:
const observer = new IntersectionObserver ( entries => {
entries. forEach ( entry => {
if (entry.isIntersecting) {
square.classList. add together ( 'foursquare-transition' ) ;
return ;
}

square.classList. remove ( 'square-transition' ) ;
} ) ;
} ) ;

observer. detect (document. querySelector ( '.square-wrapper' ) ) ;

And here's the finished demo. The CSS transition is triggered when the wrapper element is scrolled in and out of view. If the JS fails, the element volition still be visible.

As you lot tin encounter, this technique can exist extended in many ways to create a bunch of cool animations. Remember, your animations should be quick, usually less than half a second. I've slowed down the animations in this mail so that they are easier to come across for learning purposes. If y'all copy any of this code, be sure to make the animations faster.

If you found this post helpful, check out all of my curlicue animation articles.

You don't have to start from scratch...

Become the whorl animation starter pack. Driblet your email below and yous'll instantly get...

  • The copy and paste starter code for whatever curl animation
  • The text-highlight scroll blitheness you can employ correct now (and how it's made)
  • 10 existent-world websites to find whorl blitheness inspiration

Source: https://coolcssanimation.com/how-to-trigger-a-css-animation-on-scroll/

Posted by: kernsurvis.blogspot.com

0 Response to "How To Trigger Css Animation On Scroll"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel