Following up on other article, I’d like to show how to do some animations in JavaScript.
The Key to Animations
Personally, it helps me to think about animations in states:
INITIAL
- before anything has happenedSTART
- when your animation actually startsANIMATING
- everything that happens while the animation is going onFINISHED
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 = {
INITIAL: "INITIAL",
START: "START",
ANIMATING: "ANIMATING",
FINISHED: "FINISHED",
};
// 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);
}