Read more

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

Nico Winkler
January 19, 2024Software engineer at makandra GmbH

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 
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Nico Winkler to makandra dev (2024-01-19 13:40)