Comparing CSS and Web Animations

This is a comparison between CSS code and JavaScript code that use the Web Animations API to achieve the same effects. If you are already familiar with defining CSS animations, you will feel right at home with the Web Animations API.

Looped color animation

CSS

.rainbow {
    animation: rainbow 2s alternate infinite;
}

@keyframes rainbow {
    0% { background: #ff004d; }
    20% { background: #ff77ab; }
    50% { background: #00e756; }
    80% { background: #29adff; }
    100% { background: #ff77ab;}
}

Web Animations API

let el = document.querySelector('.rainbow');
el.animate([
    { background: '#ff004d', offset: 0 },
    { background: '#ff77ab', offset: 0.20 },
    { background: '#00e756', offset: 0.5 },
    { background: '#29adff', offset: 0.80 },
    { background: '#ff77ab', offset: 1 }
], {
    duration: 2000,
    direction: 'alternate',
    iterations: Infinity
});

Linear transform with user events

CSS

Mouse over the button

button {
    transform: scale(1);
    transition: all 0.5s;
}

button:hover {
    transform: scale(1.25);
}

Web Animations API

Mouse over the button

let el = document.querySelector('.animated');
el.addEventListener('mouseover', function () {
    let anim = el.animate({
        transform: ['scale(1)', 'scale(1.25)']
    }, 300);
    el.style.transform = 'scale(1.25)';
});
el.addEventListener('mouseout', function () {
    let anim = el.animate({
        transform: ['scale(1.25)', 'scale(1)']
    }, 300);
    el.style.transform = '';
});