Sub topic 14
The JavaScript API: ScrollTimeline and ViewTimeline
This chapter assumes you know @keyframes, the animation-timeline property, scroll() and view(), and how scroll containers work. It shows how to create the same timelines from JavaScript with the Web Animations API (WAAPI).
Why use the JavaScript API
CSS covers most scroll-driven effects. JavaScript helps when you need to create animations at runtime, change keyframes or ranges based on data, or keep a handle on the animation to pause, reverse, or cancel it.
Two classes map to the CSS functions:
| CSS | JavaScript |
|---|---|
| `scroll()` or `scroll-timeline` | `new ScrollTimeline({ source, axis })` |
| `view()` or `view-timeline` | `new ViewTimeline({ subject, axis, inset })` |
| `animation-timeline` | the `timeline` option of `Element.animate()` |
A scroll progress timeline
A ScrollTimeline needs a source, which is the scroll container whose offset drives progress. Use document.documentElement for the page scroller. The axis option accepts block, inline, x, or y, and defaults to block.
const timeline = new ScrollTimeline({
source: document.documentElement,
axis: 'block'
});
document.querySelector('.progress').animate(
{ transform: ['scaleX(0)', 'scaleX(1)'] },
{ timeline, fill: 'both', easing: 'linear' }
);This matches the CSS progress bar from earlier in the tutorial. Two details differ from time-driven animations:
- Do not set
duration. Progress comes from scroll position, so the timeline controls it. - Keep
easing: 'linear'. The default easing in WAAPI is alreadylinear, but writing it makes the intent clear.
A view progress timeline
A ViewTimeline tracks how much of a subject element is visible in its nearest scroll container. Pass subject, and optionally axis and inset.
const cards = document.querySelectorAll('.card');
for (const card of cards) {
const timeline = new ViewTimeline({ subject: card, axis: 'block' });
card.animate(
{
opacity: [0, 1],
transform: ['translateY(40px)', 'none']
},
{
timeline,
fill: 'both',
easing: 'linear',
rangeStart: 'entry 0%',
rangeEnd: 'cover 30%'
}
);
}rangeStart and rangeEnd are the WAAPI equivalent of animation-range. They take the same range names and percentages as the CSS version.
Feature detection
Browsers that lack scroll timelines throw a ReferenceError when you use the constructors. Check first, and respect the reduced-motion preference as you would in CSS.
const canScrollAnimate = 'ScrollTimeline' in window;
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (canScrollAnimate && !reduceMotion) {
const timeline = new ScrollTimeline({ source: document.documentElement });
document.querySelector('.progress').animate(
{ transform: ['scaleX(0)', 'scaleX(1)'] },
{ timeline, fill: 'both' }
);
}Common errors
- No
fill. Withoutfill: 'both', the element snaps back to its original style outside the active range. - Setting a
duration. A numeric duration is ignored or, in some cases, rejected for scroll timelines. Leave it out. - Wrong
source. If the source does not actually scroll (no overflow), progress stays at 0. - Reading time-based values. For a scroll-driven animation,
animation.currentTimeis a progress value (a CSS percentage-like number), not milliseconds. Useanimation.timeline.currentTimeto read it.
Exercises
Exercise
You want a ScrollTimeline for a scrollable div with class .list, tracking horizontal scrolling. Write the constructor call.
Show answer
new ScrollTimeline({ source: document.querySelector('.list'), axis: 'inline' }). The value 'x' also works, and 'inline' follows the writing mode.
Exercise
A card animation created with ViewTimeline jumps back to its start style once the card has fully scrolled past. Which option fixes this?
Show answer
Add fill: 'both' (or 'forwards') to the options passed to animate(), so the end state persists outside the active range.