Home >Web Front-end >CSS Tutorial >How Can I Detect the Completion of CSS3 Transitions and Animations with jQuery?

How Can I Detect the Completion of CSS3 Transitions and Animations with jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-12-27 16:08:15403browse

How Can I Detect the Completion of CSS3 Transitions and Animations with jQuery?

Waiting for CSS3 Transitions with jQuery

When using CSS3 transitions to animate elements, determining when the animation has completed can be challenging. Unlike jQuery animations, which allow for callbacks when animations finish, CSS3 transitions do not provide such a mechanism. However, there is a solution using jQuery.

Detecting Transition Completion

jQuery provides event listeners that can be used to detect the end of CSS3 transitions. These listeners are:

  • transitionend
  • webkitTransitionEnd
  • oTransitionEnd
  • MSTransitionEnd

You can bind to these events using the bind() method on the selector you wish to track. For example:

$("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
    // Code to execute when the transition ends
});

Detecting Animation Completion

Similar to transitions, animations can also be detected using jQuery event listeners:

  • animationend
  • webkitAnimationEnd
  • oAnimationEnd
  • MSAnimationEnd

Use the bind() method as before:

$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){
    // Code to execute when the animation ends
});

One-Time Event Firing

To ensure the event handler only fires once, use jQuery's .one() method:

$("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
    // Code to execute when the transition ends
});

$("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){
    // Code to execute when the animation ends
});

Best Practices

  • Pass all browser-prefixed event strings into the bind() method to support all browsers.
  • Use .one() to prevent the handler from firing multiple times.
  • jQuery's bind() method is deprecated; on() is preferred as of version 1.7.
  • Alternatively, use off() to detach the callback after the event fires to ensure it fires only once.

The above is the detailed content of How Can I Detect the Completion of CSS3 Transitions and Animations with jQuery?. 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