Recipe 8.6

Making an Element Bounce

This replicates a bouncing icon effect such as the one in macOS by moving the element up and down again. The animation is repeated three times, each with a smaller transformation value, so that it appears to bounce.

Demo

Code

JavaScript
const button = document.querySelector('#bounce-trigger');
const ball = document.querySelector('#bounce');

// The distance the element moves is smaller each time.
const distances = [ '40px', '20px', '10px' ];

async function animateBounce() {
  for (let distance of distances) {
    // Wait for this animation to complete before continuing
    await ball.animate([
      // Start at the bottom
      { transform: 'translateY(0)' }, 

      // Move up by the current distance
      { transform: `translateY(-${distance})`, offset: 0.5 },

      // Back to the bottom
      { transform: 'translateY(0)' }
    ], {
      duration: 250,
      easing: 'ease-in-out'
    }).finished;
  }
}

button.addEventListener('click', async () => {
  button.disabled = true;
  await animateBounce();
  button.disabled = false;
});
HTML
<style>
  #bounce {
    margin-top: 2rem;
  }
</style>

<div class="d-flex flex-column align-items-center">
  <button id="bounce-trigger" class="btn btn-primary">Bounce!</button>
  <div id="bounce">
    <i class="fs-1 bi bi-envelope"></i>
  </div>
</div>
Web API Cookbook
Joe Attardi