Animations: CSS vs JavaScript
Goal
The main goal of this article is to make a comparison between CSS and JavaScript in order to create animations, providing pro and cons and when it's convenient to opt for one approach or the other. Besides, we will be looking into a few examples of simple transitions and animations with CSS and JavaScript.
Let's begin by displaying a few examples of basic transitions with both approaches:
Code
Using CSS.
Using JavaScript.
On the second block of code, in order to pull off a similar output using JavaScript, we need to add event listeners (onmouseover, onmouseout) to the buttons, and define scripts so as to update the element styles on such event listeners.
So far, it doesn't seem much of a difference in terms of complexity, later on we will be looking into a more complex animation.
Pros and Cons
JavaScript:
- JavaScript-based animation delivers far more flexibility, power and better workflow for complex animations and rich interactivity, as JavaScript is imperative - you are able to programmatically define the animation - .
- Creating animations with JavaScript is, by comparison, more complex than writing CSS transitions or animations
CSS:
- They're easy to use for simple animations; you can start creating without the need of having to know about JavaScript.The animations run well, even under moderate system load. Simple animations can often perform poorly in JavaScript. The rendering engine can use frame-skipping and other techniques to keep the performance as smooth as possible.
- Letting the browser take the control of the animation sequence lets the browser optimize performance and efficiency by, for example, reducing the update frequency of animations running in tabs that aren't currently visible.
If you can do an animation with CSS over JavaScript, don't think it twice.
More examples
In this example, we will be producing an animation using JavaScript to move an element from left to right infinitely:
However, we can also use CSS in order to achieve a similar result, by defining @keyframes to take control of the animation sequence.
In this code block, we've described the animation declaratively: its start position, end position, duration, etc. This tells the browser ahead of time the behavior of the animation, indicating which CSS properties will be modified.
Animating SVG with CSS.
We can also animate SVG assets using CSS, here's an example:
Conclusions
We can use either CSS or JavaScript to create animations. What we opt to use will depend on the complexity of the animation and rich interactivity we may need.
We should always try to create our animations using CSS where possible. If the animations we are to create are really complex, we may have to rely on JavaScript-based animations (or JavaScript libraries) instead.