Evan Byrne

Evan Byrne

CSS Animations With Javascript

October 17, 2013

Animations should be done with CSS instead of Javascript when possible for a couple reasons. Firstly, CSS animations often use the GPU. Secondly, style definitions naturally belong in the CSS stylesheet and not in Javascript. So why do people use Javascript to animate web elements? Well, Javascript allows our websites to respond to browser events in ways that CSS doesn't. This means that we can't just do away with Javascript entirely.

Meeting In The Middle

To apply animations first define classes in CSS for the animations and then add/remove those classes from elements using Javascript. Here's the obligatory jQuery example:

.foo {
    color: black;
    transition: color 0.5s;
}

.animate-red {
    color: red;
}
$('.foo').click(function(e) {
    e.preventDefault();
    $(this).toggleClass('animate-red');
});

Pretty simple, right? Clicking on the .foo element will cause its color to transition between black and red. I imagine that not everything can be animated this way though, so keep an open mind.

Note: It is also possible to move transition: color 0.5s; over to the .animate-red definition, but that would cause the animation to only run when the class is added. The transition back to black would then be instant when the class is removed.