Skip to content
jshacks.dev
Browser

JavaScript transitionend Event: When It Fires, How to Use It

When the JavaScript transitionend event fires, why it fires once per property and bubbles, how to avoid missed events, and when to use animation promises.

7 min read
Summarize in AI
Flat illustration of one event fanning out to several listeners, with the JavaScript, Google Chrome and Node.js logos.

A CSS transition changes a property smoothly over time: a panel slides open, a button fades, a card grows. Often the code that starts the transition also needs to know when it is over, to remove an element that has faded out, to focus a field in a panel that has finished opening or to start the next step. The transitionend event is the signal for that. It fires on the element when a transition finishes, and it has behaviors that make it harder than it looks: it fires once for each property that was animated, it bubbles from children, it does not fire at all if the transition never runs, and it is not the same as the end of the whole sequence. This post explains how the JavaScript transitionend event works: its properties, how to filter by property and target, the cases where it never fires, how to wait for it safely with a timeout and with promises, how it relates to transitionrun, transitionstart and transitioncancel, how to handle display and the hidden attribute, and when element.animate() and getAnimations() are better tools. It is defined in CSS Transitions, documented on MDN, and supported in every current browser.

The basic event

A TransitionEvent fires on the transitioning element when a transition ends. It carries propertyName, elapsedTime in seconds and pseudoElement, which is an empty string unless the transition ran on a pseudo-element.

basic.jsJavaScript
document.body.innerHTML = `
  <style>
    .box { width: 50px; height: 50px; background: teal; transition: width 300ms, opacity 300ms; }
    .box.open { width: 200px; opacity: 0.5; }
  </style>
  <div class="box"></div>
`;

const box = document.querySelector(".box");

box.addEventListener("transitionend", (event) => {
  console.log(event.propertyName, event.elapsedTime);
});

box.classList.add("open");
Text
width 0.3
opacity 0.3

Two properties changed, so two events fired, one for width and one for opacity, each with its own duration. The order depends on the timing, and for equal durations on the order in which the browser processes them. A handler that assumes a single event runs its logic twice.

Filter by property and target

Because the event fires once per property, check which one you are waiting for. And because it bubbles, check that it came from the element you care about and not from a child that has its own transition, or your handler will fire early.

filter.jsJavaScript
box.addEventListener("transitionend", (event) => {
  if (event.target !== event.currentTarget) return;
  if (event.propertyName !== "width") return;
  console.log("width finished");
});
Text
width finished

The target check uses event.target !== event.currentTarget, which is true for events that bubbled up from descendants. A shorthand such as transition: all makes the number of events hard to predict, since every changed property fires its own, so avoid all where script depends on the end, and list the properties instead. For a transition on margin or padding, the browser fires events for the longhand properties, such as margin-top, not for the shorthand, which is another reason to filter on a specific, known property.

When it never fires

The event is not guaranteed. If the transition never starts, there is no end to report. The cases to know are:

SituationWhy no transitionend
The property value does not changeThere is nothing to animate
The duration is 0s or no transition is declaredThe change is instant
The element is display: none when the change happensIt has no rendering, so it does not transition
The property is not animatable, such as display in older browsersNo interpolation
The element is removed from the DOM mid-transitionThe transition is canceled
A new change interrupts ittransitioncancel fires instead
The user prefers reduced motion and the CSS removes transitionsDuration is zero

Code that waits for transitionend and never gets it hangs, so every wait needs an escape. The common one is a timeout slightly longer than the transition, which makes sure the next step runs.

safe.jsJavaScript
function afterTransition(element, property, fallbackMs = 500) {
  return new Promise((resolve) => {
    let finished = false;

    const done = () => {
      if (finished) return;
      finished = true;
      element.removeEventListener("transitionend", onEnd);
      element.removeEventListener("transitioncancel", done);
      clearTimeout(timer);
      resolve();
    };

    const onEnd = (event) => {
      if (event.target === element && event.propertyName === property) done();
    };

    element.addEventListener("transitionend", onEnd);
    element.addEventListener("transitioncancel", done);
    const timer = setTimeout(done, fallbackMs);
  });
}

box.classList.toggle("open");
afterTransition(box, "width").then(() => console.log("next step"));
Text
next step

The helper resolves once, whether the transition ends, is canceled or never starts, and it cleans up its listeners. Set the fallback to the transition's duration plus a margin, and read the duration from CSS if it can change.

duration.jsJavaScript
function totalMs(element) {
  const style = getComputedStyle(element);
  const parse = (value) =>
    value.split(",").map((s) => (s.includes("ms") ? parseFloat(s) : parseFloat(s) * 1000));

  const durations = parse(style.transitionDuration);
  const delays = parse(style.transitionDelay);
  return Math.max(...durations.map((d, i) => d + (delays[i % delays.length] ?? 0)));
}

console.log(totalMs(box));
Text
300

The family of transition events

Four events cover the life of a transition.

EventFires when
transitionrunThe transition is created, before any delay
transitionstartThe delay is over and the transition begins to run
transitionendIt finishes
transitioncancelIt is interrupted before finishing
lifecycle.jsJavaScript
for (const name of ["transitionrun", "transitionstart", "transitionend", "transitioncancel"]) {
  box.addEventListener(name, (event) => {
    if (event.propertyName === "width") console.log(name);
  });
}

box.classList.add("open");
Text
transitionrun
transitionstart
transitionend

If the user toggles the class again halfway, the first transition ends with transitioncancel, not transitionend, and a new one starts from the current value. Code that cleans up on transitionend only, leaves state behind in that case, so handle both, as the helper above does.

Removing an element after it fades

The classic use is fade-out then remove. Start the transition by adding a class, and remove the element when it ends.

remove.jsJavaScript
function fadeAndRemove(element) {
  element.style.transition = "opacity 200ms";
  element.style.opacity = "0";

  element.addEventListener(
    "transitionend",
    (event) => {
      if (event.propertyName === "opacity") element.remove();
    },
    { once: true },
  );
}

const toast = document.createElement("div");
toast.textContent = "Saved";
document.body.append(toast);
getComputedStyle(toast).opacity;
fadeAndRemove(toast);
Text
(the toast fades over 200 ms and is then removed)

The line that reads getComputedStyle(toast).opacity forces the browser to compute the starting style, which is necessary when an element was just inserted and its first style has not been calculated, otherwise the change from the default to 0 may be applied as the initial state and no transition runs. This "force a style flush before the change" trick is the usual explanation when a transition on a new element does nothing. The modern alternative is @starting-style in CSS, which declares the starting values of a new element so the transition runs without that trick.

Hidden and display none

A transition cannot animate to display: none, because the element disappears at the first frame. The older answers were to wait for transitionend and then set display: none or the hidden attribute. Current CSS can animate display and overlay with transition-behavior: allow-discrete, which keeps the element rendered until the end and then hides it, and in that case the usual transitionend listener is unnecessary.

hidden.jsJavaScript
panel.classList.remove("open");

panel.addEventListener(
  "transitionend",
  (event) => {
    if (event.propertyName === "opacity" && !panel.classList.contains("open")) {
      panel.hidden = true;
    }
  },
  { once: true },
);
Text
(the panel is hidden after its fade-out has completed, so assistive technology no longer reaches it)

Hiding with the hidden attribute after the transition matters for accessibility: an element that is only transparent stays in the accessibility tree and in the tab order, so keyboard users can reach invisible controls.

Promises and the Web Animations API

CSS transitions are exposed as CSSTransition objects in the Web Animations API. Call element.getAnimations() and wait for their finished promises, which resolve at the end and reject on cancel, with no event bookkeeping.

animations.jsJavaScript
async function transitionsFinished(element) {
  const transitions = element.getAnimations().filter((a) => a instanceof CSSTransition);
  await Promise.allSettled(transitions.map((a) => a.finished));
}

box.classList.toggle("open");
transitionsFinished(box).then(() => console.log("all transitions done"));
Text
all transitions done

This waits for all running transitions together and handles cancellation with allSettled, and it returns at once if nothing is running. Note that getAnimations() reflects the state after the style change is processed, so call it after the class change, and in some cases after a frame. For script-driven motion, element.animate() returns an animation with a finished promise from the start, which is easier than a transition plus an event.

Reduced motion

Respect the user's setting in CSS by shortening or removing transitions under @media (prefers-reduced-motion: reduce). When you do, transitionend stops firing for those changes, which is another reason a wait must have a fallback, or better, use getAnimations(), which simply finds nothing to wait for.

reduced.cssCSS
@media (prefers-reduced-motion: reduce) {
  .box {
    transition: none;
  }
}
Text
(changes apply instantly and no transition events are fired)

Testing

In a unit test environment without a real rendering engine, transitions do not run, so transitionend never fires. Dispatch it yourself with new TransitionEvent("transitionend", { propertyName: "opacity", bubbles: true }) to test the handler. In a real browser test, wait for the event or for getAnimations() to settle, and set the duration to a very short value through a test stylesheet to keep the tests fast.

test.jsJavaScript
const el = document.createElement("div");
document.body.append(el);

el.addEventListener("transitionend", (event) => console.log(event.propertyName));
el.dispatchEvent(new TransitionEvent("transitionend", { propertyName: "opacity", bubbles: true }));
Text
opacity

Pitfalls

Assuming one event per transition. Not filtering bubbling events from children. Waiting for transitionend when it may never fire. Forgetting transitioncancel. Using transition: all and then reacting to the wrong property. Leaving listeners attached, which then fire for later, unrelated transitions, so use { once: true } or remove them. Applying display: none at the start of a fade-out. And relying on a transition event for correctness when the user has reduced motion on.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.