You should be using the Web Animations API

Posted . Visible to the public. Repeats.

The Web Animations API Show archive.org snapshot has great browser support Show archive.org snapshot , and you should be using it to animate DOM elements from JavaScript, or to control or wait for CSS animations.

Here is a quick overview of a few useful features:

Animating elements from JavaScript

Use the Element#animate() Show archive.org snapshot function to perform animations on an element.

Its API probably a bit different from how your favorite frontend framework animates, but simple enough to get used to.
Like for CSS animations, you specify keyframes to animate. This can be as simple as a tuple of start and end state.

const keyframes = [
  { opacity: 0 },
  { opacity: 1 },
]
const animation = element.animate(keyframes, { duration: 1000 })

After the animation has finished, the animation keyframes will be cleared from the element and it will return to its previous state.
You can specify the iterations: Infinity option to loop animations (like with CSS animations).

An Animation object is returned that you can use to further control the animation.

Waiting for animations to finish

Animation#finished Show archive.org snapshot returns a promise that allows you to wait for animations to finish.

const animation = element.animate(keyframes, { duration: 1000 })
await animation.finished
alert('animation finished!')

Side note: When animations are cancelled, the promise is rejected.

Forcing animations to finish

You can use Animation#cancel() Show archive.org snapshot to cancel animations that are currently in progress.

As mentioned above, this clears keyframes from the element. The element will return to its pre-animation state.
This may be different from frontend frameworks where cancelling animations would force them to reach the final state.

Accessing currently running all animations and CSS transitions

With Element#getAnimations() Show archive.org snapshot you get an Array of all Animations and CSS transitions that are currently running on an element.

element.getAnimations()
// returns e.g. [Animation, CSSTransition]

CSSTransition Show archive.org snapshot inherits from Animation Show archive.org snapshot , so you can await or cancel them in the same way.
This is great when your JavaScript wants to wait for an element to e.g. fade in or out via CSS. You don't need to know anything about the element's CSS transition definitions or durations.

await Promise.all(element.getAnimations().map(animation => animation.finished))
Arne Hartherz
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2024-02-16 10:59)