banner



How To Do A Scrolling Animation In Html

How to trigger a CSS blitheness on scroll

past Nick Ciliak on

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

Triggering a CSS animation on scroll is a type of scroll-triggered animation. When people say "on whorl", what they usually mean is "when the chemical element is scrolled into view". This tutorial will cover 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'south get-go by creating a CSS animation. CSS animations are defined by keyframes.

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

You tin name your animation annihilation you want. I've defined an animation where the element will grow wide and then tall.

Once your keyframes are divers, y'all can use the blitheness on an element by setting the animation-proper noun property to the name of your keyframes. You'll also need to fix an animation-elapsing 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-movement                :                no-preference)                            {              
.foursquare {
animation-proper name : wipe-enter;
blitheness-duration : 1s;
animation-iteration-count : infinite;
}
}

I've wrapped the course in the prefers-reduced-motion: no-preference media query. This makes certain that our animation merely runs if the user has non enabled the "reduce motion" setting on their operating system.

For this demo, I've created a foursquare element that will be animated. Here'southward what information technology looks similar:

Y'all can also set up your CSS animation using a unmarried autograph animation property like this:

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

Control the CSS blitheness with a class

Nosotros don't want the blitheness to play correct away. We tin control when the animation is played past adding the animation properties to a split class than the grade used to style the element.

                          .foursquare              {              
width : 200px;
height : 200px;
background : orangish;
// etc...
}

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

When nosotros add the blitheness form to the square, the animation will play. Try it:

You'll find that the animation doesn't play every time you click the button. That's considering the CSS animation will only trigger when the foursquare-blitheness class is added, non removed.

Fifty-fifty though the animation shows the element entering, the element is visible earlier the animation class is added. When the page get-go loads, nosotros desire the element to exist 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 past adding the grade to our element. Instead of adding and removing the class when a button is clicked, nosotros tin add it when the chemical element is scrolled into view.

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

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

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

The Intersection Observer API lets you keep track of when one chemical element intersects with an another and tells you when that happens. That's perfect for triggering a CSS animation on scroll. Nosotros want to know when our square intersects with the viewport. If it is intersecting, that means the square is in view and we should trigger our animation.

If you're familiar with result listeners in JavaScript, you tin think of Intersection Observer as a fancy issue listener with some extra options. Instead of attaching an event listener to an chemical element, nosotros tell the observer to continue track of the element and where information technology is on the folio.

Let'southward start by creating an observer and have it keep track of our square:

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

// Tell the observer which elements to track
observer. observe (certificate. querySelector ( '.square' ) ) ;

By default, the root element that will be checked for intersection is the browser viewport, so we only demand to tell the observer almost our square.

When the callback part runs, it gives united states of america an entries assortment of the target elements we asked it to scout, plus some additional information about them. It will ever paw back an array, even if you only observe 1 element like we are here.

In the callback, we tin can loop over the array of entries to specify what we want to practice. Each entry has an isIntersecting property that will exist truthful or false. If it's true, that means the chemical element is visible within the viewport.

            entries.              forEach              (              entry              =>              {              
if (entry.isIntersecting) {
// It'southward visible. Add the blitheness class hither!
}
} ) ;

Let's put it all together. Annotation that entry is the object given to us by the observer and entry.target is the actual element that we are observing, then that's where nosotros should utilize the course.

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

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

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

If you want the blitheness to play every fourth dimension the element enters the viewport, yous need to remove the animation form when the chemical element is no longer intersecting.

If the element you are animating changes size or position, information technology can be tricky for the browser to make up one's mind if the chemical element is currently in or out of the viewport. It'southward best to wrap the chemical element you want to breathing in an element that won't modify size or position and use that i for your observer instead of the chemical element you are animating.

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

And so we notice the square-wrapper element and apply the class to the square like we did previously. If the wrapper is non intersecting, we tin can remove the class from the foursquare so that the blitheness will 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) {
foursquare.classList. add together ( 'square-animation' ) ;
return ; // if nosotros added the class, exit the office
}

// Nosotros're not intersecting, so remove the class!
foursquare.classList. remove ( 'square-blitheness' ) ;
} ) ;
} ) ;

observer. observe (certificate. querySelector ( '.foursquare-wrapper' ) ) ;

Now the square will animate every time the wrapper element enters the viewport. I've fabricated the wrapper chemical element visible past giving it a dashed edge. Attempt scrolling up and downwards over the demo below.

Success! Past adding and removing a CSS class when the element enters and leaves the viewport, nosotros've successfully triggered a CSS blitheness on ringlet.

The Scroll Blitheness Handbook

8 prepare-fabricated scroll animations that volition strengthen your site'south message

Check it out

Trigger a CSS transition on scroll

If your animation only has one pace, such equally fading an element's opacity from 0 to ane, you lot can use a CSS transition instead of a CSS animation.

The method is essentially the aforementioned. Instead of defining keyframes for our blitheness class, we ascertain the properties we want to transition.

                          .square              {              
width : 200px;
height : 200px;
background : teal;
border-radius : 8px;
opacity : 0;
transform : scale (1.two) ;
}

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

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

Permit'southward have some other foursquare and have information technology fade in when it enters the viewport. You can see I've already added the square-transition grade to the HTML. That'due south because if the user has JavaScript blocked or it fails to load, they should run into the chemical element in its final transitioned country.

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

This is peculiarly important since nosotros are starting from opacity: 0. If we didn't accept the square-transition class setup and the JavaScript fails, the user wouldn't encounter the element at all! If your transition is to make something fade out, you probably wouldn't want to practise this.

When the JavaScript get-go runs, nosotros can remove the class so it tin can be added dorsum when we 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 code:

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

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

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

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

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

As you tin see, this technique tin can be 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 downwardly the animations in this mail service then that they are easier to see for learning purposes. If yous copy any of this lawmaking, be sure to brand the animations faster.

If you establish this postal service helpful, check out all of my scroll animation articles.

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

Get the roll blitheness starter pack. Drop your email beneath and y'all'll instantly go...

  • The re-create and paste starter code for any whorl animation
  • The text-highlight ringlet animation you tin can use right now (and how information technology's made)
  • ten real-world websites to find gyre animation inspiration

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

Posted by: williamstharrife.blogspot.com

0 Response to "How To Do A Scrolling Animation In Html"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel