Animation Event Driven Animation

Using animation events to drive update frames.

by Kye Hohenberger

CSS

@keyframes tickAnimation {
  from {
    opacity: 1;
  }
  to {
    opacity: 1;
  }
}

JavaScript

const a = document.createElement('div')
a.style.width = '50vw'
a.style.height = '50vh'
a.style.background = '#38d9a9'
a.style.color = '#087f5b'

// The duration of the animation determines the `tick` interval
a.style.animation = '128ms linear 0ms infinite alternate tickAnimation'
a.style.animationPlayState = 'running'
a.addEventListener(
  'animationiteration',
  function () {
    // console.log('iteration')
    update(Math.random())
  },
  false
)


const ball = document.createElement('div')
ball.style.width = '5vw'
ball.style.height = '5vw'
ball.style.background = '#e6fcf5'
ball.style.borderRadius = '50%'
ball.style.position = 'absolute'
ball.style.top = '0'
ball.style.left = '0'

a.appendChild(ball)

function update (val) {
  ball.style.webkitTransform = `translate3d(calc(${val} * 50vw), calc(${val} * 50vh), 0)`
  ball.style.transition = 'transform cubic-bezier(0.13, 0.33, 0.23, 1.71) 512ms'
}

update(Math.random())
document.body.appendChild(a)