Animation Events
You learned in the last chapter that when a transition completes, it generates a DOM event. Animations also fire events. They fire an event at the start and end of an animation as well as the end of each iteration.
Types of Animation Events
Transitions fire an event only when the transition ends. Animations can fire any of three possible events:
- An animationstart event fires when the animation starts. If a positive animation-delay has been set, the event fires when the delay ends. If the delay is negative, the event fires immediately with an elapsedTime equal to the absolute value of the delay.
- An animationend event fires when the animation completes. This event is similar to the transitionend event.
- An animationiteration event fires at the end of each iteration of an animation, except the last one when an animationend event fires instead. This means animations with zero or one iteration won’t fire an animationiteration event.
For transitions the transitionend event offers three read-only values. Similarly there are three read-only values you can access with animation events:
- animationName is the value of the animation-name property of the animation that fired the event.
- elapsedTime is the amount of time the animation has been running, in seconds, when this transitionend event fires. This time excludes any time the animation was paused. The elapsedTime for an animationstart event is 0.0s.
- pseudoElement is the name (beginning with two colons) of the CSS pseudo-element on which the animation runs or an empty string if the animation runs directly on an element. At the moment only Firefox version 23 and newer supports reading this value, but in practice I’ve yet to get it working.
Animations can have multiple properties animating at the same time. These can be properties set on a single animation or on multiple animations. An event is generated for each animation-name value and not for each individual property being animated.
As long as an animation has a valid @keyframes rule and a nonzero duration, it generates events, even if the @keyframes rule is empty.
Let’s try an example so we can experiment with these events and their associated values. You’ve been working with variations of the same example. Why stop now? You’ve made the box slide to the right and most of the time back to the left. Let’s add another @keyframes rule that generates a downward slide. You’ll apply this new rule after the .box finishes the slide animation.
The animation will slide to the right, slide back to its initial position, and then slide down and back up again (EXAMPLE 4.11).
Add div with a class of box and an id of box to your HTML.
The class is used to style the div like you’ve been doing all along, and the id is used to hook into the element via JavaScript. The class name and id name don’t need to be the same. You just need to make sure to match the names you give them in the appropriate place in the code.
<div class="box" id="box"></div>
Give the .box div dimensions and a background color so you can see it on the page, and then add an animation using the animation shorthand.
.box { width: 200px; height: 200px; background-color: #393; -webkit-animation: slide 2s linear 0s 2 alternate both; animation: slide 2s linear 0s 2 alternate both; }
Before creating the @keyframes rule, take a look at the shorthand in this code, and make sense of what it’s doing. It’s calling an @keyframes rule named slide. Each animation cycle runs a total of 2 seconds. The timing is linear so there is no acceleration. There’s no delay, and the animation completes two cycles. It runs once normally and then runs in reverse. Animation elements hold their state both before and after the animation runs.
Create the @keyframes rule using translation to move the element 600 pixels to the right.
@-webkit-keyframes slide { 100% { -webkit-transform: translate(600px, 0px); -ms-transform: translate(600px, 0px); transform: translate(600px, 0px); } } @keyframes slide { 100% { -webkit-transform: translate(600px, 0px); -ms-transform: translate(600px, 0px); transform: translate(600px, 0px); } }
Load the page in a browser.
The familiar green .box slides to the right and then slides back left to its starting point. This animation fires events. You’ll capture those events using a little JavaScript. Don’t worry, it’s no more complicated than what you did in the last chapter with transition events, and you’re free to copy the code.
What you’re going to do is listen for one of the animation events and when it occurs, start a second animation. The .box is probably getting tired of sliding across the page so a slidedown @keyframes rule seems in order.
Create an @keyframes rule for a new slidedown animation. Add a translation transform, and make the .box move 300 pixels down the screen.
@-webkit-keyframes slidedown { to { -webkit-transform: translate(0px, 300px); -ms-transform: translate(0px, 300px); transform: translate(0px, 300px); } } @keyframes slidedown { to { -webkit-transform: translate(0px, 300px); -ms-transform: translate(0px, 300px); transform: translate(0px, 300px); } }
You can reload your page if you’d like, but I’ll save the suspense. Nothing changes. You’ve created a @keyframe rule, but it’s not attached to any element yet. That’s where the events and JavaScript come in.
Add the following JavaScript between <script></script> tags in the head of your document:
<script> var init = function() { var box = document.getElementById("box"); box.addEventListener("webkitAnimationStart", updateAnimation , false); box.addEventListener("oTAnimationStart", updateAnimation , false); box.addEventListener("animationstart", updateAnimation , false); function updateAnimation (e) { box.style.webkitAnimationName = "slidedown"; box.style.animationName = "slidedown"; } }; window.addEventListener('DOMContentLoaded', init, false); </script>
The JavaScript is a modified version of what you saw with transition events. The last line of code, window.addEventListener('DOMContentLoaded', init, false);, once again runs an init function after the page content loads.
In the init function, you first get the element with an id of box and assign it to a variable named box. Next, you add an event listener (with and without vendor prefixes) to the box to capture an animationstart event. When the event is captured, it’s passed to an updateAnimation function. Finally the updateAnimation function changes the animation-name value to the slidedown animation created in step 5.
Reload your page, and observe what happens.
The second animation (slidedown) runs, but the first one (slide) doesn’t. This happens because the JavaScript captures the event that fires at the start of the animation and changes which animation is used before slide can run.
Let’s capture a different event (EXAMPLE 4.12).
Change your JavaScript to listen for animationiteration, and change its vendor-prefixed variations. Changes in the code are highlighted.
<script> var init = function() { var box = document.getElementById("box");
box.addEventListener("webkitAnimationIteration", updateAnimation , false);
box.addEventListener("oTAnimationIteration", updateAnimation , false);
box.addEventListener("animationiteration", updateAnimation , false);
function updateAnimation (e) { box.style.webkitAnimationName = "slidedown"; box.style.animationName = "slidedown"; } }; window.addEventListener('DOMContentLoaded', init, false); </script>Reload your page.
The slide animation starts and completes a single cycle before it jumps back to its initial state and begins and completes both iterations of the slidedown animation.
This time you listened for the event that fires at the end of each iteration of an animation. The slide animation completes one iteration, the animationiteration event is fired, and your code starts the slidedown animation. The slidedown animation completes because the JavaScript code runs only a single time. No code is listening for the events that the slidedown animation fires in this example.
Change your JavaScript code to listen for animationend, and change its vendor-prefixed variations (EXAMPLE 4.13). Changes in the code are highlighted.
<script> var init = function() { var box = document.getElementById("box");
box.addEventListener("webkitAnimationEnd", updateAnimation , false);
box.addEventListener("oTAnimationEnd", updateAnimation , false);
box.addEventListener("animationend", updateAnimation , false);
function updateAnimation (e) { box.style.webkitAnimationName = "slidedown"; box.style.animationName = "slidedown"; } }; window.addEventListener('DOMContentLoaded', init, false); </script>Reload the page.
This time both animations start and complete. First slide moves the .box to the right before returning. As soon as it completes, an animationend event is fired. Your JavaScript hears the event and starts the slidedown animation, which also completes.
FIGURE 4.10 summarizes listening for each of the three animation events and starting the slidedown animation after the slide events fire.
FIGURE 4.10 Animation events summary
Let’s do one more thing: read the read-only values. You can access and read them at each of the three fired events.
Change your JavaScript code to listen for the animationstart event, and set an alert to display the animationName that fired the event and the elapsedTime it’s been running. Changes in the code are highlighted.
<script> var init = function() { var box = document.getElementById("box");
box.addEventListener("webkitAnimationStart", updateAnimation , false);
box.addEventListener("oAnimationStart", updateAnimation , false);
box.addEventListener("animationstart", updateAnimation , false);
function updateAnimation (e) {
alert("The " + e.animationName + " animation has been running for " + e.elapsedTime + "s");
}
}; window.addEventListener('DOMContentLoaded', init, false); </script>Reload your page.
As soon as the page loads, the slide animation runs, and an alert pops up with the message, “The slide animation has been running for 0s.”
FIGURE 4.11 shows the alerts that display when listening for the animationiteration event.
FIGURE 4.11 Animation event read-only values
Experiment by changing which event is listened for. Change animationstart to animationiteration, then to animationend (and their vendor-prefixed variants), and observe the differences. When listening for the animationiteration event, your alert should read “The slide animation has been running for 2s,” and when listening for the animationend event it should read “The slide animation has been running for 4s.”