Course contentsShow
← Web Development
Lesson 527 of 2,9829. CSS Transitions and AnimationsFree lesson

Animation Events in JavaScript

Listen for animationstart, animationend, and animationiteration events to synchronize logic.

Animation Events in JavaScript

You'll learn how to listen for animation lifecycle events so your JavaScript can respond when CSS animations start, loop, or finish.

What Are Animation Events?

Just like transitions, CSS animations fire JavaScript events at key moments. This lets you synchronize code execution with your animations—imagine triggering a sound effect when an animation completes, or updating state when a looping animation repeats.

The Three Animation Events

CSS animations trigger three distinct events:

  • animationstart – Fires when an animation begins (after any animation-delay)
  • animationend – Fires when an animation completes naturally
  • animationiteration – Fires each time a looping animation restarts (except the first iteration)

These events fire on the element being animated, so you can attach listeners directly to it.

How to Listen for Animation Events

const box = document.querySelector('.animated-box');

box.addEventListener('animationstart', (event) => {
  console.log(`Animation "${event.animationName}" started!`);
});

box.addEventListener('animationiteration', (event) => {
  console.log(`Animation looped at ${event.elapsedTime}s`);
});

box.addEventListener('animationend', (event) => {
  console.log(`Animation finished after ${event.elapsedTime}s`);
  // Now you can safely update UI or trigger next action
});

Each event object includes useful properties like animationName (which animation fired) and elapsedTime (how long it's been running).

Why This Matters

Animation events bridge CSS and JavaScript, letting you create sophisticated interactions. You can chain animations, update application state, remove elements after they fade out, or trigger analytics—all timed perfectly with your visual effects.

Key Takeaway: Use animationstart, animationend, and animationiteration event listeners to synchronize JavaScript logic with CSS animation lifecycles.