Recipe 8.4

Reversing Animations

Hover over the button, and it will start getting larger. If you move the mouse away before the animation completes, it will immediately reverse and run in the opposite direction for a seamless visual transition. Similarly, if the button is shrinking and you move the mouse back over it, it will start to grow again.

You can play with this by moving the mouse back and forth quickly onto and off of the button to see the animation keep reversing indefinitely.

Demo

Code

JavaScript
const button = document.querySelector('.hover-button');

let animation;

async function animate(direction) {
  if (animation) {
    animation.reverse();
  } else {
    animation = button.animate([
      { transform: 'scale(1)' },
      { transform: 'scale(2)' }
    ], { duration: 1000, fill: 'forwards', direction });

    await animation.finished;
    animation = null;
  }
}

button.addEventListener('mouseover', () => {
  animate('normal');
});

button.addEventListener('mouseout', () => {
  animate('reverse');
});
HTML
<button class="hover-button btn btn-primary">Hover me</button>
Web API Cookbook
Joe Attardi