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

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

DDD
DDDOriginal
2024-11-04 07:35:02435browse

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

Detecting the Completion of CSS3 Transitions and Animations Using jQuery

Transitioning elements with CSS3 offers smoother animations than traditional JavaScript techniques. However, when working with CSS3 animations, the question arises: how can you determine when the transition has completed?

jQuery provides a solution for this need. To monitor the end of a CSS3 transition, you can bind an event handler using the following syntax:

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

Similarly, for CSS3 animations, you can use:

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

By providing all the browser-prefixed event strings in the bind() method, you ensure compatibility across browsers.

Ensuring Single Execution of the Handler

To prevent repeated execution of the handler, you can employ jQuery's .one() method. For instance:

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

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

Depreciation of .bind() Method

jQuery's bind() method has been deprecated in favor of .on(). Therefore, you should use:

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

This method also ensures that the handler is executed only once.

For further details, refer to the following references:

  • [jQuery .off()](https://api.jquery.com/off/)
  • [jQuery .one()](https://api.jquery.com/one/)

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