Skip to content

Instantly share code, notes, and snippets.

@preyneyv
Last active January 12, 2020 11:23
Show Gist options
  • Select an option

  • Save preyneyv/8183f056611eb403fc1b92debb117630 to your computer and use it in GitHub Desktop.

Select an option

Save preyneyv/8183f056611eb403fc1b92debb117630 to your computer and use it in GitHub Desktop.

Control CSS animation with scrolling

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment