Recipe 8.2
Pausing and Resuming Animations
Demo
Code
JavaScript
const trigger = document.querySelector('.trigger');
const box = document.querySelector('.box');
const animation = box.animate([
{ transform: 'rotate(0deg)' },
{ transform: 'rotate(360deg)' }
], { duration: 5000, iterations: Infinity });
function toggleAnimation(animation) {
if (animation.playState === 'running') {
animation.pause();
trigger.textContent = 'Animate';
} else {
animation.play();
trigger.textContent = 'Pause';
}
}
trigger.addEventListener('click', () => {
toggleAnimation(animation);
});
HTML
<style>
.box {
background: skyblue;
width: 64px;
height: 64px;
margin-right: 2rem;
}
</style>
<div class="d-flex align-items-center">
<div class="box"></div>
<button class="trigger btn btn-primary">Pause</button>
</div>