Inside out bouncing ball animation

by Génesis García Morilla

HTML

<div class="box"></div>

CSS

body {
  margin: 0;
  display: grid;
  min-block-size: 100svh;
}

.box {
  display: grid;
  width: 300px;
  margin: auto;
  aspect-ratio: 1;
  border: 5px solid darkgrey;
  overflow: hidden;
}

.box::before {
  content: '';
  width: 30px;
  aspect-ratio: 1;
  margin: auto;
  border-radius: 50%;
  background: green;
  animation: out 500ms forwards;
}

.box:hover::before {
  animation: inside 500ms forwards;
}

@keyframes inside {
  from {
    translate: 0 0;
  }
  to {
    translate: var(--x) var(--y);
  }
}

@keyframes out {
  from {
    translate: var(--x) var(--y);
  }
  to {
    translate: 0 0;
  }
}

JavaScript

const box = document.querySelector('.box')

box.onmousemove = e => {
  // because we're starting in the middle
  const x = e.offsetX - box.offsetWidth / 2
  const y = e.offsetY - box.offsetHeight / 2

  box.style.setProperty('--x', `${x}px`)
  box.style.setProperty('--y', `${y}px`)
}