Home >Web Front-end >CSS Tutorial >How Can I Detect the Completion of a CSS Transition?

How Can I Detect the Completion of a CSS Transition?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 15:51:10426browse

How Can I Detect the Completion of a CSS Transition?

Callback on CSS Transition

Question:

Is it possible to receive a notification when a CSS transition has completed?

Answer:

Yes, if supported by the browser, an event is triggered when the transition ends. However, the specific event varies across browsers:

  • Webkit browsers (Chrome, Safari): webkitTransitionEnd
  • Firefox: transitionend
  • IE9 : msTransitionEnd
  • Opera: oTransitionEnd

Additional Considerations:

  • webkitTransitionEnd may not always trigger, especially if the animation has no effect on the element.
  • A timeout fallback is recommended to ensure the event handler is called in case the event doesn't fire as expected.

Code Example:

const transitionEndEventName = "XXX"; // Determine the appropriate event name
const elemToAnimate = ...; // Element to animate
let done = false;
const transitionEnded = () => {
  done = true;
  // Transition finished actions
  elemToAnimate.removeEventListener(transitionEndEventName, transitionEnded, false);
};
elemToAnimate.addEventListener(transitionEndEventName, transitionEnded, false);

// Trigger animation

setTimeout(() => {
  if (!done) {
    console.log("Timeout required to call transition ended.");
    transitionEnded();
  }
}, XXX); // Replace XXX with animation duration plus a grace period

Note:

  • The transition event end name can be obtained using the method discussed in the answer to "How do I normalize CSS3 Transition functions across browsers?"
  • This issue is also related to "CSS3 transition events."

The above is the detailed content of How Can I Detect the Completion of a CSS Transition?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn