You might have heard of RxJS, or ReactiveX, or reactive programming, or even just functional programming before. These are terms that are becoming more and more prominent when talking about the latest-and-greatest front-end technologies. And if you’re anything like me, you were completely bewildered when you first tried learning about it.
Despite its name, reactive animations have nothing to do with React, the framework/library/whatever it is. Rather, reactive animations can be described in terms of discrete changes caused by any number of events.
The overall idea is that JS captures multiple streams of events into a single stream, and emits those values over to CSS, where they are expressed as custom properties. By doing this, we can accomplish reactive styles.
The result is RxCSS, “a very small library for manipulating CSS Custom Properties (aka CSS Variables) with RxJS Observables”.
Observing the scroll offset in an element could be coded as such:
// Observe scrolling in .content
const content = document
const scroll$ = Rx.Observable
2 * target.scrollTop / target.clientHeight);
// Couple the result of the `scroll$` observable to the `scroll` CSS Variable
In your CSS you can then use the scroll CSS Variable like one would normally do:
// Fade out background photo + scale it up when scrolling up one screen
opacity: calc(1 - var(--scroll));
transform: scale(calc(1 + var(--scroll) / 3));
// Fade in the content when scrolling up
opacity: var(--scroll, 0);