The HTML onanimationcancel event
The HTML onanimationcancel attribute runs JavaScript when a CSS animation is unexpectedly aborted. It is an inline handler for the animationcancel event; in modern code prefer addEventListener('animationcancel', …).
Overview
The onanimationcancel event attribute runs JavaScript when a CSS animation is canceled. In JavaScript the event itself is named animationcancel — drop the on prefix when you call addEventListener.
It is a CSS animation event. The handler receives an AnimationEvent with the animationName and elapsedTime, letting you run code at specific points in a CSS animation defined with @keyframes.
You can wire this up with the inline onanimationcancel HTML attribute, but the modern, recommended approach is element.addEventListener('animationcancel', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Syntax
<element onanimationcancel="handler()">…</element>
element.addEventListener('animationcancel', handler);
Best practices
- Prefer
element.addEventListener('animationcancel', handler)over the inlineonanimationcancelattribute — it separates behavior from markup and allows multiple handlers. - Use it to run JavaScript at a precise point in a CSS animation without a timer.
- Check
event.animationNamewhen an element has more than one animation. - Respect
prefers-reduced-motionfor the animations these events track.
Frequently asked questions
What is the onanimationcancel event?
animationcancel.How do I run code when a CSS animation finishes?
How do I know which animation triggered the event?
event.animationName from the AnimationEvent.Should I use the onanimationcancel attribute or addEventListener?
addEventListener('animationcancel', …) in JavaScript. The inline onanimationcancel attribute works but mixes behavior into the markup and allows only one handler per element.