6.1 · Motion
Animate on scroll: scroll-driven animations
Drive animations with scrolling instead of time.
An animation normally runs on time.
animation-timeline ties it to scrolling instead.
scroll() follows a scroll container’s position, which
suits a reading progress bar. view() follows an element
as it crosses the viewport, which suits reveal effects.
animation-range picks the part of the journey:
entry 0% cover 40% runs from the moment the element
enters until it covers 40% of the view.
window.addEventListener('scroll', () => {
const p = scrollY / (scrollHeight - innerHeight)
bar.style.transform = `scaleX(${p})`
})
// + IntersectionObserver for reveals
.progress {
animation: grow linear both;
animation-timeline: scroll(root);
}
.card {
animation: reveal linear both;
animation-timeline: view();
animation-range: entry 0% cover 40%;
}