Detecting the Completion of CSS3 Transitions and Animations with jQuery
In web development, it's often desirable to perform an action after a CSS transition or animation has completed. However, determining the exact end of these animations can be tricky. This article will demonstrate how to use jQuery to detect the completion of both transitions and animations, ensuring precise control over DOM manipulation.
Transitions
To detect the end of a CSS transition via jQuery, utilize the following syntax:
$("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
This binds an event handler to the specified element that triggers when any of the supported transition end events occur.
Animations
For CSS animations, a similar approach is used:
$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
Ensuring One-Time Firing
To prevent the event handler from running multiple times, use jQuery's .one() method. This ensures the handler fires only once, after which it is automatically removed:
$("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... }); $("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
jQuery Method Deprecation
Note that the .bind() method has been deprecated in jQuery 1.7. Use .on() instead:
$("#someSelector") .on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(e){ // do something here $(this).off(e); } );
This equivalent code uses .off() to effectively mimic the behavior of .one().
References:
The above is the detailed content of How Can jQuery Detect the Completion of CSS3 Transitions and Animations?. For more information, please follow other related articles on the PHP Chinese website!