Transcript
[00:00] One interesting feature of the Web Animations API is we have access to a timeline for our animation. I’m going to go ahead and kill off all these buttons that we’re controlling the pause, play, and reverse. And we’re going to keep this range control, though. So, okay, so right now this controls the speed, and we’re going to tweak that.
[00:23] But what I’m going to do here is right after I’ve instantiated our animation, I don’t want it to fire, so I’m going to pause it right there. Whoops. Pause. So it’s going to pause immediately. So on our animation, we have access to something called current time. And I can set that. So here I’ll say 250. So I know that our animation lasts 1,000 milliseconds. I’m setting it to 250 milliseconds. And there it is, about a quarter of the way through our animation.
[00:56] So what we’re going to do is we’re going to repurpose this range input and set its value, or its initial value, to 0. And on the min, we’ll start at 0. On the max, we’ll go to 1,000, which represents our 1,000 milliseconds. And the step will now be 1. And down here, rather than updating the playback rate, we’re going to update the current time. So I’ll save that. And now I can scrub through our animation.
[01:25] So here we are approaching 500. We can go all the way to the end. And I can come all the way back. And we can scrub through it much like we would a video.
Learn how to control and scrub through Web Animations API timelines in JavaScript like a pro. This tutorial shows you to pause, set initial states, and build custom playback controls for precise front-end animation management.
<html><head> <style> body { background-color: #222; } .container { display: flex; justify-content: center; } .circle { width: 200px; height: 200px; border-radius: 100%; border: 4px solid #fff; border-top: 4px solid blue; } #playback { display: flex; flex-direction: column; justify-content: center; align-items: center; } #current { color: #fff; } </style></head><body> <div class="container"> <div class="circle"></div> </div> <div id="playback"> <div> <input value="0" id="range" type="range" min="0" max="1000" step="1"> </div> <div id="current">0</div> </div>
<script> const myAnimation = document.querySelector(".circle").animate( [ { transform: "rotate(0)" }, { transform: "rotate(359deg)" } ], { duration: 1000, iterations: Infinity } );
myAnimation.pause();
document.getElementById("range").addEventListener("input", e => { const value = e.target.value; document.getElementById("current").innerText = value; myAnimation.currentTime = +value; }); </script></body></html>