Web Animations API: Programmatic Animations Without CSS Keyframe Classes

The Web Animations API: CSS-quality animations controlled from JavaScript

Animations that depend on data, such as a counter that moves to a value from the REST API, a card that flies to the cart, or an animation that must be paused, reversed or awaited, are clumsy with CSS classes: the script adds a class, listens for animationend and removes it again. element.animate() runs the same kind of animation as CSS keyframes, on the compositor where possible, and returns an Animation object with play(), pause(), reverse() and a finished promise.

Problem: A shop theme animates the product image flying into the mini cart after “Add to cart”. The current code clones the image, sets inline styles, adds a class with a CSS animation, waits for animationend with a timeout fallback, and sometimes leaves clones on the page when the event does not fire.

Solution: Compute the start and end positions, animate a clone with element.animate() using transform and opacity keyframes, wait for animation.finished before removing it, and skip the movement when the visitor prefers reduced motion.

The fly-to-cart animation

async function haFlyToCart( image, cartIcon ) {
    const from = image.getBoundingClientRect();
    const to = cartIcon.getBoundingClientRect();

    const clone = image.cloneNode();
    Object.assign( clone.style, {
        position: 'fixed',
        left: `${ from.left }px`,
        top: `${ from.top }px`,
        width: `${ from.width }px`,
        height: `${ from.height }px`,
        margin: 0,
        zIndex: 9999,
        pointerEvents: 'none',
    } );
    document.body.append( clone );

    const dx = to.left + to.width / 2 - ( from.left + from.width / 2 );
    const dy = to.top + to.height / 2 - ( from.top + from.height / 2 );
    const reduce = matchMedia( '(prefers-reduced-motion: reduce)' ).matches;

    const animation = clone.animate(
        [
            { transform: 'translate(0, 0) scale(1)', opacity: 1 },
            { transform: `translate(${ dx }px, ${ dy }px) scale(.1)`, opacity: .3 },
        ],
        { duration: reduce ? 1 : 600, easing: 'cubic-bezier(.5, 0, .75, 0)' }
    );

    try {
        await animation.finished;
    } finally {
        clone.remove();
    }

    cartIcon.animate(
        [ { transform: 'scale(1)' }, { transform: 'scale(1.25)' }, { transform: 'scale(1)' } ],
        { duration: reduce ? 1 : 300 }
    );
}

The keyframes are the same as in CSS, written as an array of objects. animation.finished resolves when the animation ends and rejects when it is cancelled; finally removes the clone in both cases, so no leftovers stay on the page. transform and opacity run on the compositor and stay smooth even while the main thread processes the AJAX response.

Hook it into WooCommerce

jQuery( document.body ).on( 'adding_to_cart', ( event, button ) => {
    const card = button[ 0 ].closest( '.product' );
    const image = card?.querySelector( 'img' );
    const cart = document.querySelector( '.ha-mini-cart-icon' );
    if ( image && cart ) haFlyToCart( image, cart );
} );

adding_to_cart is WooCommerce’s jQuery event before the AJAX request of archive “Add to cart” buttons. Bridging such events to native code: CustomEvent and EventTarget.

Control and reuse

const spinner = icon.animate( [ { rotate: '0deg' }, { rotate: '360deg' } ], { duration: 1000, iterations: Infinity } );
spinner.pause();
spinner.play();
spinner.playbackRate = 2;      // twice as fast
spinner.cancel();              // remove its effect

document.getAnimations();      // all running animations, including CSS ones

getAnimations() also returns CSS animations and transitions as Animation objects, so a script can pause or finish them, for example to wait until a CSS transition of a menu is done: await Promise.all( menu.getAnimations().map( ( a ) => a.finished ) ).

NOTE: The Web Animations API with finished, getAnimations() and composite modes is supported in all current browsers since 2020. Declarative effects that depend only on state (hover, open, visible) are still simpler in CSS: CSS animations and keyframes.