Animations on scroll
The simple and nice trick of coupling CSS animations with vertical scrolling...
... is inspired by the solution of Scott Kellum.
Important: While the animation state is set to pause, it is animated by setting a negative animation-delay
.
body {
background: transparent url(background.svg) no-repeat;
background-position: 0 0;
background-attachment: fixed;
background-size: 150vw;
animation: event-background 5s linear infinite;
animation-play-state: paused;
animation-delay: calc(var(--scroll) * -1s);
}
/* the animation */
@keyframes event-background {
100% {
background-position: 100% 0;
}
}
The window’s scroll property is continuously read out and made globally accessible as the CSS variable --scroll
.
function respondSetScroll() {
document.body.style.setProperty('--scroll', window.pageYOffset / (document.body.offsetHeight - window.innerHeight));
}
// set offset on scroll
window.addEventListener('scroll', respondSetScroll, false);
?