Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Toggle Animation Play/Pause</title> </head> <body> <h1>Toggle Play/Pause Animation</h1> <div class="animated-element" style="width: 100px; height: 100px; background-color: green" ></div> <button style="margin-top: 15px" onclick="togglePlayPause()">Toggle Play/Pause</button> <p id="message"></p> <script> let animation; document.addEventListener("DOMContentLoaded", function () { const element = document.querySelector(".animated-element"); animation = element.animate( { opacity: [0, 1] }, { duration: 1000, easing: "ease-in-out" } ); animation.pause(); // Start paused animation.onfinish = () => { document.getElementById("message").textContent = "Animation finished!"; }; }); function togglePlayPause() { if (animation.playState === "running") { animation.pause(); document.getElementById("message").textContent = "Animation paused"; } else { animation.play(); document.getElementById("message").textContent = "Animation playing"; } } </script> </body> </html>