Home > Article > Web Front-end > How to Detect the End of CSS3 Transitions and Animations in jQuery?
Monitoring Completion of CSS3 Transitions and Animations in jQuery
In web development, it's often desirable to fade out an element and subsequently remove it from the DOM upon animation completion. While this is straightforward with jQuery's animation capabilities, extending it to CSS3 transitions requires a mechanism to detect their conclusion.
Thankfully, jQuery provides avenues to address this issue:
Transitions
To detect the end of a CSS transition via jQuery, utilize the following event binders:
$("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
Mozilla elaborates further on this at https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions#Detecting_the_start_and_completion_of_a_transition
Animations
For animations, the approach is similar:
$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
A crucial point to note is that, by employing the bind() method with all the browser-prefixed event strings concurrently, you can ensure support for all browsers with this functionality.
Optimizing Event Handling
To restrict handler firing to a single occurrence, use jQuery's .one() method, like so:
$("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... }); $("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
Method Deprecation and Modern Alternatives
It's worth acknowledging that jQuery's bind() method has been deprecated as of jQuery 1.7 in favor of the on() method. Additionally, you can leverage the off() method within the callback function to guarantee a one-time execution, as demonstrated in this example:
$("#someSelector") .on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(e){ // do something here $(this).off(e); });
This approach has the same effect as using the one() method.
Additional Resources
The above is the detailed content of How to Detect the End of CSS3 Transitions and Animations in jQuery?. For more information, please follow other related articles on the PHP Chinese website!