This example uses the addEventListener()
method to attach an "animationstart", "animationiteration" and "animationend" event to a DIV element.
<!DOCTYPE html> <html> <head> <style> #myDIV {/* www.j av a2 s .c o m*/ margin: 25px; width: 550px; height: 100px; background: orange; position: relative; font-size: 20px; } /* Chrome, Safari, Opera */ @-webkit-keyframes mymove { from {top: 0px;} to {top: 200px;} } @keyframes mymove { from {top: 0px;} to {top: 200px;} } </style> </head> <body> <div id="myDIV" onclick="myFunction()">Click me to start the animation.</div> <script> var x = document.getElementById("myDIV"); // Start the animation with JavaScript function myFunction() { x.style.WebkitAnimation = "mymove 4s 2"; // Code for Chrome, Safari and Opera x.style.animation = "mymove 4s 2"; // Standard syntax } // Code for Chrome, Safari and Opera x.addEventListener("webkitAnimationStart", myStartFunction); x.addEventListener("webkitAnimationIteration", myRepeatFunction); x.addEventListener("webkitAnimationEnd", myEndFunction); // Standard syntax x.addEventListener("animationstart", myStartFunction); x.addEventListener("animationiteration", myRepeatFunction); x.addEventListener("animationend", myEndFunction); function myStartFunction() { this.innerHTML = "animationstart event occurred - The animation has started"; this.style.backgroundColor = "pink"; } function myRepeatFunction() { this.innerHTML = "animationiteration event occurred - The animation was played again"; this.style.backgroundColor = "lightblue"; } function myEndFunction() { this.innerHTML = "animationend event occurred - The animation has completed"; this.style.backgroundColor = "lightgray"; } </script> </body> </html>
The animationstart event occurs when a CSS animation has started to play.
When a CSS animation plays, there are three events that can occur:
Event | Description |
---|---|
animationstart | occurs when the CSS animation has started |
animationiteration | occurs when the CSS animation is repeated |
animationend | occurs when the CSS animation has completed |