Sub topic 3
Listening for CSS Motion Events and Controlling Performance
Assume you know CSS selectors, pseudo-classes, common properties, and how JavaScript toggles a class. This chapter focuses on motion that finishes reliably, stays smooth, and respects user preferences.
Listening for `transitionend` and `animationend`
A transition can finish once for each property. Check propertyName when several properties transition. A keyframe animation emits animationend after an iteration completes, unless it is canceled.
const button = document.querySelector(".button");
button.addEventListener("transitionend", (event) => {
if (event.propertyName === "transform") {
console.log("Button movement finished");
}
});
button.addEventListener("animationend", (event) => {
console.log(`${event.animationName} finished`);
});The events do not fire when motion is removed before completion, such as when display: none is applied.
Keeping motion smooth
Prefer transform and opacity. Browsers can often update these without recalculating surrounding layout. Animating width, height, top, or margin may trigger layout and paint work for many elements.
Smooth motion also depends on modest durations and avoiding too many simultaneous effects.
Respecting reduced motion
prefers-reduced-motion reports a user's system preference. Remove decorative motion while preserving state changes and clear focus indicators.
@media (prefers-reduced-motion: reduce) {
.button {
transition: none;
}
.badge {
animation: none;
}
}Inspecting motion in developer tools
Use the browser's Elements panel to check which rule supplies transition, animation, or transform. Toggle classes manually and inspect computed styles. Many browser developer tools include an Animations panel where you can pause, scrub, slow, and inspect keyframes. If motion does not run, check that the trigger changes a value, the element is rendered, and a reduced-motion rule is not disabling it.
Entry effects and the Web Animations API
@starting-style supplies an initial value when an element first appears. Discrete properties, such as display, do not interpolate through normal numeric values, but modern CSS can transition them with allow-discrete.
.dialog {
display: none;
opacity: 0;
transition: opacity 300ms ease-out, display 0s allow-discrete;
}
.dialog.open {
display: block;
opacity: 1;
}
@starting-style {
.dialog.open {
opacity: 0;
}
}For JavaScript-controlled motion, the Web Animations API uses keyframes and timing options:
document.querySelector(".card").animate(
[{ opacity: 0 }, { opacity: 1 }],
{ duration: 300, easing: "ease-out", fill: "both" }
);Exercise
Why should a transitionend handler check event.propertyName?
Show answer
One transition can emit an event for each transitioned property, so the check prevents unrelated properties from triggering the handler.