Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect when CSS animations start and end with JavaScript?

Tags:

I was used to animating elements with JavaScript. I found it simpler to do it with CSS3.

Using JavaScript how can you detect when a CSS animation has started and when it has ended? Is there any way at all?

like image 642
Alex Avatar asked Feb 10 '13 10:02

Alex


People also ask

How to detect the events of CSS animation in JavaScript?

With JavaScript, it possible to detect the events (start, restart and end) of CSS animations. This is useful if want to perform some actions based on the animation state. To detect the animation events, we need to add the following animation event listeners to the element. animationstart – Occurs when the animation starts.

What is the difference between CSS and JavaScript animations?

CSS allows you to create animations with transitions and keyframes that once were only possible with JavaScript or Flash. Unfortunately, with CSS there’s no way to perform a callback when an animation is complete. With JavaScript, it’s possible to detect the end of a CSS transition or animation and then trigger a function.

Can you call a function from an animation in CSS?

Unfortunately, with CSS there’s no way to perform a callback when an animation is complete. With JavaScript, it’s possible to detect the end of a CSS transition or animation and then trigger a function. Handle the animations (with transitions or keyframes) in your CSS; handle the event timing and triggers in your JavaScript.

How to detect the completion of an animation using JavaScript?

You add a new event listener to the element to catch the completion of the animation. Depending on what type of animation method you use, you have to set the correct event: transitionend or animationend. To detect the events you can also use the ontransitionend and onanimationend properties.


1 Answers

Bind the appropriate events to the element, e.g.

el.addEventListener("animationstart", function() {}, false); el.addEventListener("animationend", function() {}, false); el.addEventListener("animationiteration", function() {}, false); 

https://developer.mozilla.org/en-US/docs/CSS/Tutorials/Using_CSS_animations#Using_animation_events

Note: You may need to add the appropriate prefixed-events as well, e.g. webkitAnimationEnd

like image 182
Prinzhorn Avatar answered Oct 28 '22 03:10

Prinzhorn