Skip to content

Web Animations API / lesson 2 of 7

Pause & Play

Unlock precise control over browser animations by mastering the Web Animations API pause & play

Play

Unlock precise control over browser animations by mastering the Web Animations API, enabling you to build interactive experiences that pause, play, and reverse on command. Solve the frustration of static CSS keyframes with dynamic JavaScript playback controls for a smoother, more responsive frontend development workflow.

index.html
<html>
<head>
<style>
body {
background-color: #222;
}
.container {
display: flex;
justify-content: center;
}
.circle {
width: 200px;
height: 200px;
border-radius: 100%;
background-color: #fff;
}
button {
font-size: 48px;
}
</style>
</head>
<body>
<button class="pause">Pause</button>
<button class="play">Play</button>
<div class="container">
<div class="circle"></div>
</div>
<script>
const myAnimation = document.querySelector(".circle").animate(
[
{
transform: "translateY(0)",
backgroundColor: "red"
},
{
transform: "translateY(450px)",
backgroundColor: "blue"
}
],
{
duration: 1000,
iterations: Infinity,
direction: "alternate",
easing: "ease-in-out"
}
);
document.querySelector(".pause")
.addEventListener("click", () => myAnimation.pause());
document.querySelector(".play")
.addEventListener("click", () => myAnimation.play());
</script>
</body>
</html>

Share this post on:

Previous
Introduction
Next
Reverse