animationend Retires One-Shot Animations
Wait for animationend instead of guessing durations, then remove the element with removeEventListener so CSS drives timing and JS only reacts.
Code
// CSS keeps the timing; JS just listens for the moment it finishes.
// .toast { animation: slide-in 180ms ease-out; }
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = 'Deploy started';
document.body.append(toast);
let removed = false;
function retire(event) {
if (event.target !== toast) return; // child animations bubble up
removed = true;
toast.removeEventListener('animationend', retire);
toast.remove();
}
// Fires when the toast's own animation completes — no setTimeout guesswork.
toast.addEventListener('animationend', retire);
// animationcancel covers the other exit: element hidden or animation aborted.
toast.addEventListener('animationcancel', retire);
setTimeout(() => {
console.log('toast removed by animationend:', removed);
}, 250);How the code behaves
One reading: the function retire, doing all the work.
Points of care
- The import surface (if any) is all standard library, all versioned with the language itself.
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide. - The guard
event.target !== toastcuts the flow short with an earlyreturnwhen its condition holds.
Using it
Signature: function retire(event)
Output lines are prefixed (toast removed by animationend:), so the effect of each step is right there in the output.
Core statements
toast.addEventListener('animationcancel', retire);
toast.addEventListener('animationend', retire);
setTimeout(() => {
console.log('toast removed by animationend:', removed);
}, 250);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Cubic Bezier PreviewPreview a CSS cubic-bezier() easing curve, validate the control points, and sample the progress mapping from input to output value.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does animationend Retires One-Shot Animations run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.