JavaScript animationend Event: Triggered on Animation Completion

The animationend event in JavaScript is a crucial tool for web developers working with CSS animations. It fires when a CSS animation has completed its cycle, providing a mechanism to trigger JavaScript functions upon the conclusion of an animation. This event is vital for creating more complex and interactive animations, enabling developers to control post-animation actions like resetting properties, initiating new animations, or updating the user interface. This article will explore the usage, syntax, and practical examples of the animationend event.

What is the animationend Event?

The animationend event is a DOM event that occurs when a CSS animation has finished playing. It is triggered on the HTML element where the CSS animation is applied. This event allows developers to synchronize JavaScript code execution with the completion of CSS animations, enabling them to create more dynamic and responsive user experiences.

Purpose of the animationend Event

The main purpose of the animationend event is to:

  • Synchronize actions: Execute JavaScript code immediately after an animation has finished.
  • Create animation sequences: Trigger a new animation after the current animation ends.
  • Reset properties: Change or reset element properties after an animation cycle is complete.
  • Handle user interactions: Develop interactive animation sequences based on user actions.
  • Update UI: Modify the user interface elements after the animation, ensuring a smooth transition.

Syntax of the animationend Event

The animationend event is typically used with an event listener, which allows you to execute a JavaScript function when the event occurs. Here is the basic syntax:

element.addEventListener("animationend", functionToExecute);
  • element: The HTML element on which the animation is applied.
  • addEventListener(): A method that attaches an event handler to the specified element.
  • "animationend": The name of the event being listened for.
  • functionToExecute: The JavaScript function that will be called when the animation ends.

You can also use anonymous functions or arrow functions as the event handler:

element.addEventListener("animationend", function (event) {
  // Code to execute
});

// or
element.addEventListener("animationend", (event) => {
  // Code to execute
});

animationend Event Attributes

The animationend event provides an event object with several useful properties, inherited from the AnimationEvent interface:

Property Type Description
`animationName` String Returns the name of the CSS animation that has finished.
`elapsedTime` Number Returns the amount of time the animation has been running, in seconds, when the event was fired.
`target` Element Returns the element that triggered the animation event.
`type` String Returns the type of the event which is `”animationend”` in this case.
`timeStamp` Number Returns the timestamp at which the event occurred.
`eventPhase` Number Returns the phase of the event flow which is `2` (AT_TARGET) for an animationend event.
`currentTarget` Element Returns the element whose event listener triggered the event.

Practical Examples of the animationend Event

Let’s dive into practical examples demonstrating how to use the animationend event in different scenarios.

Basic Usage: Alert on Animation End

In this first example, we’ll demonstrate how to display an alert message when a simple animation has completed on a div element.

<div
  id="animatedDiv1"
  style="
    width: 100px;
    height: 100px;
    background-color: lightblue;
    animation: moveDiv 2s linear;
  "
></div>
<script>
  const animatedDiv1 = document.getElementById("animatedDiv1");
  animatedDiv1.addEventListener("animationend", (event) => {
    alert("Animation ended!");
  });
</script>
<style>
  @keyframes moveDiv {
    from {
      transform: translateX(0);
    }
    to {
      transform: translateX(200px);
    }
  }
</style>

When you run the above code, the div element will move horizontally and once the animation finishes, an alert box will appear on the screen.

Changing Styles After Animation End

Here, we’ll show how to change the background color of an element after its animation ends, providing a visual indication of completion.

<div
  id="animatedDiv2"
  style="
    width: 100px;
    height: 100px;
    background-color: lightgreen;
    animation: fadeOut 1s linear;
  "
></div>
<script>
  const animatedDiv2 = document.getElementById("animatedDiv2");
  animatedDiv2.addEventListener("animationend", (event) => {
    animatedDiv2.style.backgroundColor = "lightcoral";
  });
</script>
<style>
  @keyframes fadeOut {
    from {
      opacity: 1;
    }
    to {
      opacity: 0.1;
    }
  }
</style>

In the above example, the div element will fade out during the animation. Once finished, its background color changes to lightcoral.

Triggering a New Animation After the Previous Ends

In this example, we demonstrate how to chain animations, starting a new one after the previous one ends, creating a continuous motion.

<div
  id="animatedDiv3"
  style="
    width: 50px;
    height: 50px;
    background-color: lightpink;
    position: relative;
    animation: moveLeft 1s linear;
  "
></div>
<script>
  const animatedDiv3 = document.getElementById("animatedDiv3");
  animatedDiv3.addEventListener("animationend", (event) => {
    if (event.animationName === "moveLeft") {
      animatedDiv3.style.animation = "moveRight 1s linear";
    } else if (event.animationName === "moveRight") {
      animatedDiv3.style.animation = "moveLeft 1s linear";
    }
  });
</script>
<style>
  @keyframes moveLeft {
    from {
      left: 0;
    }
    to {
      left: 100px;
    }
  }
  @keyframes moveRight {
    from {
      left: 100px;
    }
    to {
      left: 0;
    }
  }
</style>

The code above makes the div element move horizontally back and forth continuously.

Using the animationName Property

This example shows how to use the animationName property of the event to handle different animations on the same element. This allows for complex animation sequences.

<div
  id="animatedDiv4"
  style="
    width: 70px;
    height: 70px;
    background-color: lightskyblue;
    animation: rotate1 2s linear;
  "
></div>
<script>
  const animatedDiv4 = document.getElementById("animatedDiv4");
  animatedDiv4.addEventListener("animationend", (event) => {
    if (event.animationName === "rotate1") {
      animatedDiv4.style.animation = "rotate2 2s linear";
      animatedDiv4.style.backgroundColor = "lightgoldenrodyellow";
    } else if (event.animationName === "rotate2") {
      animatedDiv4.style.animation = "rotate1 2s linear";
      animatedDiv4.style.backgroundColor = "lightskyblue";
    }
  });
</script>
<style>
  @keyframes rotate1 {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(180deg);
    }
  }
  @keyframes rotate2 {
    from {
      transform: rotate(180deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
</style>

The div element in this example rotates and changes color alternatively between the two animations on each animationend event.

Using elapsedTime Property

Here we demonstrate using elapsedTime property. It’s useful when you want to check how much time the animation has taken during an animation end.

<div
  id="animatedDiv5"
  style="
    width: 70px;
    height: 70px;
    background-color: lightseagreen;
    animation: scaleAnimation 2s linear;
  "
></div>
<script>
  const animatedDiv5 = document.getElementById("animatedDiv5");
  animatedDiv5.addEventListener("animationend", (event) => {
      alert("Animation ended after " + event.elapsedTime + " seconds.");
  });
</script>
<style>
  @keyframes scaleAnimation {
    from {
      transform: scale(1);
    }
    to {
      transform: scale(1.5);
    }
  }
</style>

In this example, when the animation on div element ends, it alerts the time that the animation took.

Browser Compatibility

The animationend event is widely supported by all modern web browsers, ensuring your animations function consistently across various platforms. 🚀

| Browser | Support |
| —————- | ——- |
| Chrome | Yes |
| Firefox | Yes |
| Safari | Yes |
| Edge | Yes |
| Opera | Yes |
| Internet Explorer | 10+ |

Best Practices

When working with the animationend event, consider the following:

  • Performance: Keep your event handlers lightweight to ensure smooth performance, avoid complex operations inside the event listener.
  • Specificity: Use the event’s animationName property to differentiate between animations if necessary, allowing you to handle each case uniquely.
  • Chaining Animations: Use the animationend event to trigger or reset animations for creating complex sequences.
  • Error Handling: Implement checks to ensure elements and animations exist before adding event listeners.
  • Testing: Always test your animations across different browsers to ensure proper functionality.
  • Accessibility: Provide alternatives to animations for users with accessibility needs.

Conclusion

The animationend event is a vital component of dynamic web animation, allowing for precise control and synchronization of JavaScript code with CSS animations. With its broad browser compatibility and versatile usage, the animationend event enables developers to create more interactive and engaging web experiences. Understanding its properties and applying it effectively will empower you to build sophisticated animations that enhance user engagement and improve the overall user experience.