Sub topic 14
The JavaScript API: ScrollTimeline and ViewTimeline
This chapter assumes you know the CSS animation-timeline property, scroll() and view(), and animation-range from the earlier chapters. It also assumes you have used Element.animate() from the Web Animations API (WAAPI). Here you will build the same scroll-driven effects in JavaScript and learn when that is worth doing.
Why a JavaScript API exists
CSS covers most scroll-driven effects. JavaScript is useful in three cases:
- You create animations at runtime, for example for elements added after page load.
- You need to read the timeline's state, such as the current scroll progress as a number.
- You want to change the scroller, the subject, or the range based on application state.
The two CSS timeline kinds each have a matching JavaScript class.
| CSS | JavaScript | What drives progress |
|---|---|---|
| `scroll()` or `scroll-timeline` | `ScrollTimeline` | Scroll position of a scroll container |
| `view()` or `view-timeline` | `ViewTimeline` | Visibility of a subject element inside its scrollport |
ViewTimeline extends ScrollTimeline, which extends AnimationTimeline. A normal document.timeline advances with the clock. These timelines advance with scrolling.
Creating a ScrollTimeline
The constructor takes an options object with two members:
source: the scroll container to track. It defaults to the document's scrolling element.axis:'block'(default),'inline','x'or'y'.
This example recreates the reading progress bar from the CSS version of the chapter.
const timeline = new ScrollTimeline({
source: document.documentElement,
axis: 'block'
});
document.querySelector('.progress').animate(
{ transform: ['scaleX(0)', 'scaleX(1)'] },
{ timeline, fill: 'both', easing: 'linear' }
);The pieces map onto the CSS version like this:
- The
timelineoption replacesanimation-timeline. - The
{ transform: [...] }object is an inline keyframe list, replacing@keyframes. fill: 'both'andeasing: 'linear'replace the same keywords in theanimationshorthand.
You do not set duration. A scroll-driven animation has no useful time length, because the timeline maps scroll distance onto the animation's whole progress. The browser handles this internally, so leave duration at its default.
The scroller must actually scroll
source must be an element that is a scroll container. If it is not scrollable, the timeline is inactive and the animation does not run. A common case is a div with overflow: auto but no content taller than its height. Another is overflow: visible, which never creates a scroll container.
Creating a ViewTimeline
A ViewTimeline tracks one element, the subject, as it moves through the scrollport of its nearest scrolling ancestor. It takes these options:
subject: the element to track. This is required.axis: the same values asScrollTimeline.inset: an adjustment to the scrollport edges, like the arguments ofview()in CSS. It is a string such as'20px'or'auto 10%', or an array of up to two values.
There is no source option. The scroller is found from the subject's position in the DOM.
const card = document.querySelector('.card');
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 JavaScript form of animation-range. They take the same named ranges (entry, exit, cover, contain) with an offset, so 'entry 0%' and 'cover 30%' match the CSS example exactly. Where animation-range takes both values in one declaration, JavaScript takes them as two separate options.
One timeline per subject
A ViewTimeline has exactly one subject. To animate a list of cards, create one timeline for each card. In CSS, view() does this for you because each element gets its own anonymous timeline.
document.querySelectorAll('.card').forEach((card) => {
const timeline = new ViewTimeline({ subject: card });
card.animate(
{ opacity: [0, 1], transform: ['translateY(40px)', 'none'] },
{
timeline,
fill: 'both',
easing: 'linear',
rangeStart: 'entry 0%',
rangeEnd: 'cover 30%'
}
);
});Reading timeline state
Reading state is the main thing JavaScript can do that CSS cannot.
timeline.currentTimeis aCSSUnitValuewith unitpercent, from 0 to 100, ornullwhen the timeline is inactive.timeline.sourceandtimeline.axisreturn the values in use.ViewTimelinealso hassubject,startOffsetandendOffset. The offsets are the scroll positions where the subject starts and stops intersecting the scrollport.
const timeline = new ScrollTimeline({ source: document.documentElement });
function report() {
const t = timeline.currentTime;
if (t === null) {
console.log('Timeline is inactive');
return;
}
console.log(`Scrolled ${t.value.toFixed(1)}%`);
}
addEventListener('scroll', report, { passive: true });
report();The scroll listener here is only for logging. The animation itself needs no listener, and that is the point of the API: the browser updates the animation without running your JavaScript on each scroll event.
Reusing and inspecting CSS-created animations
Animations created in CSS are also visible to JavaScript. element.getAnimations() returns CSSAnimation objects, and each one has a timeline property.
const [animation] = document.querySelector('.card').getAnimations();
if (animation && animation.timeline instanceof ViewTimeline) {
console.log('Subject:', animation.timeline.subject);
}You can also assign a timeline to an existing animation by setting animation.timeline = new ScrollTimeline({ ... }). Setting animation.rangeStart and animation.rangeEnd changes the active range later. This works well for responsive adjustments, such as a shorter range on small screens.
Feature detection and reduced motion
CSS support and JavaScript support do not always arrive together in every browser. Test for the classes you use, not for the browser.
const canScrollAnimate = 'ScrollTimeline' in window && 'ViewTimeline' in window;
const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
if (canScrollAnimate && !reducedMotion) {
document.querySelectorAll('.card').forEach((card) => {
const timeline = new ViewTimeline({ subject: card });
card.animate(
{ opacity: [0, 1], transform: ['translateY(40px)', 'none'] },
{
timeline,
fill: 'both',
easing: 'linear',
rangeStart: 'entry 0%',
rangeEnd: 'cover 30%'
}
);
});
}If either check fails, the cards stay in their normal, fully visible state. The check is the JavaScript counterpart of the @media and @supports wrapper used in the CSS chapter on progressive enhancement. A polyfill exists for the API, but it runs on the main thread. If you add one, decide whether the loss of smoothness is acceptable, or skip the animation instead.
Cancelling and cleaning up
Animations created with animate() keep running until cancelled. If you remove a card from the DOM, the animation goes with it. If you replace a timeline, cancel the old animation first.
const progress = document.querySelector('.progress');
const animation = progress.animate(
{ transform: ['scaleX(0)', 'scaleX(1)'] },
{
timeline: new ScrollTimeline({ source: document.documentElement }),
fill: 'both',
easing: 'linear'
}
);
document.querySelector('#stop').addEventListener('click', () => {
animation.cancel();
});After cancel(), the element returns to its unanimated style. With fill: 'both' and no cancel, it keeps the end style while the timeline is at 100%.
Choosing between CSS and JavaScript
| Situation | Prefer |
|---|---|
| Static page, fixed set of elements | CSS |
| Needs `@supports` fallback with no script | CSS |
| Elements created at runtime | JavaScript, or CSS classes added by script |
| Need to read progress as a number | JavaScript |
| Range or scroller changes with app state | JavaScript |
| Sharing a timeline across unrelated elements | CSS with `timeline-scope`, or one JavaScript timeline object passed to several `animate()` calls |
In JavaScript, sharing is simpler: one ScrollTimeline object can be passed to any number of animations, with no naming or timeline-scope needed.
Common mistakes
- Setting
durationand expecting it to control speed. Scroll distance controls speed. - Forgetting
fill: 'both', which leaves elements in their original state outside the active range. - Creating a
ViewTimelinefor an element withdisplay: none. It has no box, socurrentTimeisnull. - Passing a non-scrolling
source. - Skipping
prefers-reduced-motionchecks in script, even though you added them in CSS.
Exercise
A page has a div.panel with overflow-y: auto and a fixed height. Write the JavaScript that makes .meter scale vertically from 0 to 1 as the user scrolls the panel. Why must .panel have content taller than its height?
Show answer
const timeline = new ScrollTimeline({ source: document.querySelector('.panel'), axis: 'block' }); document.querySelector('.meter').animate({ transform: ['scaleY(0)', 'scaleY(1)'] }, { timeline, fill: 'both', easing: 'linear' }); The panel must have overflowing content because a container with nothing to scroll has no scroll range. The timeline is then inactive and the animation never progresses.
Exercise
You create new ViewTimeline({ subject: card }) and call card.animate(...) with rangeStart: 'exit 0%' and rangeEnd: 'exit 100%', then reload with the card already far above the viewport. What does the card look like, and why?
Show answer
The card shows the end keyframe. The timeline progress is past the active range, and fill: 'both' (or at least forwards) holds the final state. Without a fill mode the card would show its unanimated style.