Web Animations API / lesson 2 of 7

Pause & Play

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

Play
Transcript

[00:00] We’ve got this groovy little animation here we made in another video. I’m going to take the flex stuff off of the body here, because we’re going to add some additional elements to the page. Now we’ll just wrap this in container, save that, and everything’s looking good.

[00:33] So where web animation API differs from CSS keyframes is our ability to control the animation. We can pause it, we can play it, we can reverse it, all sorts of stuff. So I’m just going to add a button here with the class of pause, and it’ll say pause, and then we’ll do play. So there’s our buttons. Let’s make buttons a lot bigger. Yeah, that’ll work.

[01:03] Okay. So here is our animate that we created previously. We are going to assign that to a value. So I’m going to say const, myAnimation equals. Save that, and everything is going to work the way it always has. But if I come down here and I say myAnimation.pause, it’ll, I mean, it’ll pause it immediately, right? It’s paused.

[01:34] So rather than doing that, I’m going to add an event listener to my buttons. I’m going to say myAnimation.pause, and I’m going to clean this up a little bit so we can see it, and we’ll try that out. So I’ll click on pause right there, and pause it. Awesome. So we can just follow suit with the play method. So we’ll pause, and we’ll play, and it picks up right where we paused it and continues to 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