Home >Web Front-end >JS Tutorial >How to Detect the End of CSS3 Transitions and Animations with jQuery?

How to Detect the End of CSS3 Transitions and Animations with jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 06:46:30290browse

How to Detect the End of CSS3 Transitions and Animations with jQuery?

Harnessing CSS3 Transitions: Detecting Completion with jQuery

When animating elements using CSS3 transitions, it becomes necessary to know the precise moment they conclude to perform subsequent actions. Unlike jQuery animations, CSS3 transitions don't have built-in completion callbacks.

Capturing Transition End Events

To detect the end of a transition, jQuery offers the following script:

<code class="javascript">$("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });</code>

For animations, a similar approach can be used:

<code class="javascript">$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });</code>

By passing all prefixed event strings, this script will work across multiple browsers.

Using .one() for Single Fire

To ensure the event handler fires only once, you can use jQuery's .one() method instead of .bind():

<code class="javascript">$("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });

$("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });</code>

Deprecation and Modern Approach

jQuery's .bind() method is now deprecated. The preferred approach is .on(), which works in conjunction with .off(). Here's an example:

<code class="javascript">$("#someSelector")
.on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd",
 function(e){
    // do something here
    $(this).off(e);
 });</code>

This approach ensures that the callback function executes only once.

The above is the detailed content of How to Detect the End 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