Element.animate() to animate single elements with given keyframes

Today I learned that you can animate HTML elements using the Web Animation API's method .animate(keyframes, options) (which seems to be Baseline for all browsers since 2022).

const fadeIn = [{ opacity: 0 }, { opacity: 1 }] // this is a keyframe example

const container = document.querySelector('.animate-me')

const animation = container.animate(fadeIn, 2000) // I am just using the animation duration as option here but it can also be given an object

// the animation object can be used for things like querying timings or state or `pause`, `cancel` the animation
animation.pause()
animation.play()
await animation.finished

// do other stuff 

Even though play() was used in the example code above, it is not necessary for the animation to run.
The animation does wait for micro tasks to finish before executing though.

Nico Winkler 4 months ago