CSS animations are very easy to create, but they're one-shots: they can't easily be controlled by Javascript...
...until now!
/**
* Use the scroll position to control the position of a CSS animation.
* @param {string} target Selector of the target element
* @param {number} from Start position as a ratio of window height
* @param {number} to End position as a ratio of window height
*/
function scrollify(target, from, to) {
const elem = $(target);
$(window).on('scroll', function() {
const t = to * window.innerHeight;
const f = from * window.innerHeight;
const pos = $(window).scrollTop();
const animPos = Math.min(1, Math.max(0, (pos - f) / (t - f)));
elem.css('animation-delay', `-${animPos}s`);
})
}You can use it like this:
/* Define the animation you want to control */
@keyframes fadeZoomOut {
from { opacity: 1; transform: scale(1); }
to { opacity: 0; transform: scale(0.85); }
}
/* Apply it to the target element */
#target-element {
animation: 1s fadeZoomOut paused forwards;
/* Make sure the animation is:
* 1 second long
* paused
* has a fill-mode of forwards
*/
}scrollify('#target-element', 0, 1);This will cause scrolling between 0vh and 100vh to scrub through the animation.