Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Simple Opacity Animation</title> </head> <body> <h1>Simple Opacity Animation</h1> <div class="animated-element" style="width: 100px; height: 100px; background-color: blue" ></div> <button style="margin-top: 15px" onclick="startAnimation()"> Start Animation </button> <p id="message"></p> <script> let animation; function startAnimation() { const element = document.querySelector(".animated-element"); const keyframes = [ { opacity: 0, offset: 0 }, { opacity: 1, offset: 1 }, ]; const options = { duration: 1000, easing: "ease-in-out", iterations: 1, fill: "forwards", }; // Create and play the animation animation = element.animate(keyframes, options); // Handle animation events animation.onfinish = () => { document.getElementById("message").textContent = "Animation finished!"; }; animation.oncancel = () => { document.getElementById("message").textContent = "Animation reset."; }; } // Resets the animation function resetAnimation() { if (animation) { animation.cancel(); } startAnimation(); // Restart the animation } </script> </body> </html>