Sub topic 10
Listening for transitionend and animationend
CSS runs transitions and animations on its own. JavaScript often still needs to know when one finishes, for example to remove an element after it fades out, start the next step, or update state. This chapter covers the events the browser fires for that. It assumes you can write a transition and a @keyframes animation, and that you can attach an event listener and toggle a class.
The two event families
Transitions and animations each fire a set of events on the element involved.
| Event | Fires when |
|---|---|
| `transitionrun` | A transition is created, before any delay. |
| `transitionstart` | The delay has ended and the transition begins to change values. |
| `transitionend` | A transition reaches its end value. |
| `transitioncancel` | A transition is interrupted before it finishes. |
| `animationstart` | An animation begins, after its delay. |
| `animationiteration` | One iteration ends and another begins. |
| `animationend` | An animation finishes all its iterations. |
| `animationcancel` | An animation is removed before it finishes. |
In practice you will use transitionend and animationend most. The cancel events matter whenever your code waits for a finish that might never arrive.
Reading transitionend
The TransitionEvent object has three useful properties:
propertyNameis the CSS property that finished, such astransform.elapsedTimeis the transition's running time in seconds. It does not include the delay.pseudoElementis a string such as::beforeif the event came from a pseudo-element. It is an empty string for the element itself.
The event fires once for each property that transitions. A button that transitions background-color and transform fires two transitionend events. If you ignore propertyName, your handler runs twice.
const button = document.querySelector('.button');
button.addEventListener('transitionend', (event) => {
if (event.propertyName === 'transform') {
console.log('Transform transition finished');
}
});With transition: all, the number of events depends on how many properties actually changed. Filtering on propertyName is the dependable fix. Naming properties in your transition, as in the earlier chapters, also keeps this predictable.
Reading animationend
AnimationEvent has animationName, which is the name from @keyframes, plus elapsedTime and pseudoElement. Unlike a transition, an animation fires one animationend for the whole animation, not one per property. If an element runs several animations, filter on animationName.
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); }
}
.badge {
animation: pulse 500ms ease-in-out 3;
}const badge = document.querySelector('.badge');
badge.addEventListener('animationstart', (event) => {
console.log(`${event.animationName} started`);
});
badge.addEventListener('animationiteration', (event) => {
console.log(`Iteration finished at ${event.elapsedTime}s`);
});
badge.addEventListener('animationend', (event) => {
if (event.animationName === 'pulse') {
console.log(`pulse finished after ${event.elapsedTime}s`);
}
});With three iterations, animationiteration fires twice, after the first and second iterations. The third ends with animationend instead. An animation with infinite never fires animationend.
Events bubble from children
All of these events bubble. A listener on a parent also receives events from any descendant that transitions or animates. This catches many people out. A card listener may suddenly run because an icon inside it finished its own transition.
Check which element the event started from:
const card = document.querySelector('.card');
card.addEventListener('transitionend', (event) => {
if (event.target !== event.currentTarget) return;
if (event.propertyName !== 'opacity') return;
console.log('The card itself finished fading');
});Here event.target is the element that transitioned, and event.currentTarget is the element holding the listener. When they differ, the event bubbled up from a child.
When the end event never arrives
Your code must handle the cases where transitionend or animationend does not fire:
- The element or an ancestor gets
display: none. The transition or animation is cancelled, so you get a cancel event or nothing. - The property value does not change, so no transition starts.
- The duration is
0s, or the transition is removed. A transition with zero duration and zero delay does not fire events. - The user prefers reduced motion and your CSS sets
transition: noneoranimation: none. - Another state change reverses the transition midway. The first transition is cancelled, and a new one starts from the current value.
- The element is removed from the DOM before the end.
The last two cases show why you should listen for transitioncancel and animationcancel too. If your code waits for transitionend to continue and the transition is cancelled, it waits forever.
A safe remove-after-fade pattern
A common job is to fade an element out and then remove it. The risky version waits for transitionend unconditionally. This version first checks whether any animation actually started.
.toast {
opacity: 1;
transition: opacity 300ms ease-out;
}
.toast.is-leaving {
opacity: 0;
}
@media (prefers-reduced-motion: reduce) {
.toast {
transition: none;
}
}function removeToast(toast) {
toast.classList.add('is-leaving');
// getAnimations() makes the browser update styles, so a running
// CSS transition shows up in the list. Reduced motion gives an empty list.
if (toast.getAnimations().length === 0) {
toast.remove();
return;
}
const finish = () => toast.remove();
toast.addEventListener(
'transitionend',
(event) => {
if (event.target === toast && event.propertyName === 'opacity') {
finish();
}
},
{ once: true }
);
toast.addEventListener('transitioncancel', finish, { once: true });
}This works for the reduced-motion case, where no transition runs and no end event fires. One small flaw remains: once: true removes the transitionend listener after the first event of any kind. If a child's transitionend bubbles up first, your listener is spent. For production code, drop once and remove the listeners yourself once finish runs.
Wrapping an event in a promise
For sequences, a small helper turns the end event into something you can await. It resolves on either transitionend or transitioncancel, so it cannot hang on a cancel.
function waitForTransition(element, propertyName) {
return new Promise((resolve) => {
function onEvent(event) {
if (event.target !== element) return;
if (event.type === 'transitionend' && event.propertyName !== propertyName) {
return;
}
element.removeEventListener('transitionend', onEvent);
element.removeEventListener('transitioncancel', onEvent);
resolve(event.type);
}
element.addEventListener('transitionend', onEvent);
element.addEventListener('transitioncancel', onEvent);
});
}
async function openPanel(panel) {
panel.classList.add('is-open');
if (panel.getAnimations().length === 0) return;
const result = await waitForTransition(panel, 'transform');
if (result === 'transitionend') {
panel.focus();
}
}The resolved value tells the caller whether the transition finished or was cancelled. The getAnimations() check avoids waiting when nothing runs.
Events versus the Web Animations API
CSS events are the right choice when the effect is defined in a stylesheet and JavaScript only reacts. If you already control the animation from JavaScript, the Web Animations API gives you a finished promise on the Animation object. That promise rejects when the animation is cancelled. A later chapter covers that API.
Summary of rules
- Filter
transitionendbypropertyNameandanimationendbyanimationName. - Compare
event.targetwithevent.currentTargetwhen listening on a parent. - Listen for the cancel event wherever you wait for a finish.
- Check that something is running before you wait. Reduced motion, a zero duration, or an unchanged value means no event.
- Treat events as a way to react to motion. Keep the visual timing in CSS.
Exercise
A card has transition: opacity 200ms, transform 200ms and a listener card.addEventListener('transitionend', () => card.remove()). When the class is-leaving is added, the card is removed after only part of the fade finishes. Why, and how do you fix it?
Show answer
The transition covers two properties, so transitionend fires twice. Both transitions are 200ms, so the first event can remove the card while the second property is still at its end. It can also be a bubbled event from a child. Fix it by checking event.target === card and event.propertyName === 'opacity' before calling card.remove(). Also add a transitioncancel listener or a getAnimations().length === 0 check so the card is still removed when no transition runs.
Exercise
An element has animation: pulse 500ms ease-in-out 3. How many times does animationiteration fire, and does animationend fire?
Show answer
animationiteration fires twice, at the end of iterations one and two. animationend fires once, at the end of the third iteration. With infinite instead of 3, animationiteration would keep firing and animationend would never fire.
Exercise
Your code waits for transitionend after adding a class, but users with reduced motion report the interface freezes. The stylesheet sets transition: none in a prefers-reduced-motion: reduce block. What is wrong, and what is a check that fixes it?
Show answer
With transition: none no transition runs, so transitionend never fires and the waiting code never continues. Check element.getAnimations().length === 0 right after changing the class and continue immediately in that case. Listening for transitioncancel does not help here, because no transition was created to cancel.