Most basic animations can be created with either CSS or JavaScript, but the amount of effort and time will differ. Each has their pros and cons, but these are good rules-of-thumb:
-
Use CSS when you have smaller, self-contained states for UI elements.
CSS transitions and animations are ideal for bringing a navigation menu in from the side, or showing a tooltip. You may end up using JavaScript to control the states, but the animations themselves will be in your CSS.
-
Use JavaScript when you need significant control over your animations.
Something that dynamically tracks a touch position, or an animation that you need to stop, pause, slow-down or reverse typically require you to use JavaScript.
If you’re already using jQuery or a JavaScript framework that includes animation functionality then you may find it more convenient overall to stick with that for your animations than switching to CSS.
Animate with CSS
There’s no doubt that animating with CSS is the simplest way to get something moving on screen.
Below is some CSS that will move an element 100px in both the X & Y axes. It’s done by using a CSS transitions that’s set to take 500ms. When the
move
class is added the
transform
value is changed and the transition begins.
.box {
-webkit-transform: translate(0, 0);
-webkit-transition: -webkit-transform 500ms;
transform: translate(0, 0);
transition: transform 500ms;
}
.box.move {
-webkit-transform: translate(100px, 100px);
transform: translate(100px, 100px);
}
See sample
Besides the transition’s duration there are options for the easing, which is essentially how the animation feels. You can get more on that in the
“The Basics of Easing”
guide.
If, as in the above snippet, you create separate CSS classes to manage your animations, you can then use JavaScript to toggle each animation on and off:
box.classList.add('move');
Doing this will provide a very nice balance to your apps. You can focus on managing state with JavaScript, and simply set the appropriate classes on the target elements, leaving the browser to handle the animations. If you go down this route you can listen to
transitionend
events on the element, but only if you’re able to forego support for older versions of Internet Explorer; version 10 was the first version to support these events. All other browsers have supported the event for some time.
The JavaScript required to listen for the end of a transition looks like this:
var box = document.querySelector('.box');
box.addEventListener('transitionend', onTransitionEnd, false);
function onTransitionEnd() {
// Handle the transition finishing.
}
In addition to using CSS transitions, you can also use CSS animations, which will allow you to have much more control over individual animation keyframes, durations and iterations.