A visual comparison of the reduced code snippets from the article, both CSS and JS as close as they can be compared.
A cartoon skull with a hotpink hat on.2 min read

Keyframe Offsets

cssjs
1,482 views · 9 active

Well aren't keyframe offsets just super handy!

circle.animate([
  { offset: 0,   transform: 'scale(0)', opacity: 1 },
  { offset: .10, transform: 'scale(1)', opacity: 1 },
  { offset: .75, opacity: 1 },
  { offset: 1,   opacity: 0 },
])

See those useful offset values?

In CSS #

Keyframe percentages are super important in crafting animations; for both complex animations or just well orchestrated timings.

You've probably seen the % values in the keyframes.

#circle {
  animation: scale-then-fade-out 3s ease infinite;
}

@keyframes scale-then-fade-out {
  0%   { transform: scale(0); opacity: 1; }
  10%  { transform: scale(1); opacity: 1; }
  75%  { opacity: 1; }
  100% { opacity: 0; }
}

They're pretty much 2nd nature.

But I bet you've never thought to yourself, "Let me specify this keyframe offset value to 15%" 🤓 At least I hadn't, but I like the more formal name!

So… what about in JS?

In JS #

In the animate function, the keyframes are passed as an array of objects, where each object is a keyframe.

The logical place to put an offset value is right there!

circle.animate([
  { offset: 0,   transform: 'scale(0)', opacity: 1 },
  { offset: .10, transform: 'scale(1)', opacity: 1 },
  { offset: .75, opacity: 1 },
  { offset: 1,   opacity: 0 },
], {
  duration: 3000,
  easing: 'ease',
  iterations: Infinity,
})

and there you have it, the tip in this article, how to set offsets in your JS keyframe animations. At least… that's why I wrote this. Was new to me!

Try it out in this Codepen if you want to 🙂

65likes
8reposts

Join the conversation on

@a11yMel WAAPI gets to leverage all the optimizations CSS gets afaik, so yeah, no longer an issue.

it's got a sweet promise api too that plays great with `await`. can be a much nicer way to manage something complex.

Adam ArgyleAdam Argyle