Animations in Vanilla JavaScript

Following up on other article, I’d like to show how to do some animations in JavaScript.

View GitHub link here.

The Key to Animations

Personally, it helps me to think about animations in states:

  • INITIAL - before anything has happened
  • START - when your animation actually starts
  • ANIMATING - everything that happens while the animation is going on
  • FINISHED after the animation is complete

Everything and anything you’d like to do is going to take place during one or more of the states mentioned above.

Therefore, our JavaScript will fire off events for each state that can be hooked into with CSS

Code Structure

Your code should look something like this

// Define your states:
const STATES = {

// set your elements initial state:
el.setAttribute("data-animation-state", STATES.INITIAL);

// in a function, set it to animate:
async function animate() {
	// Start state is when the element is ready to animate
	el.setAttribute("data-animation-state", STATES.START);
	// The state for when it's animating
	el.setAttribute("data-animation-state", STATES.ANIMATING);
	// Waiting for the animation to finish
	await new Promise((res) => setTimeout(res, speed));
	// Setting the finished state
  el.setAttribute("data-animation-state", STATES.FINISHED);