Animator.js: JavaScript animation library

View animator.js on GitHub

Community translations:

Animator.js was a library I wrote back in 2006 to handle animation on web pages. For a time it was quite ahead of the curve: It was the first library to feature CSS morphing - the ability to smoothly transition between two styles defined as CSS classes.

The world of JavaScript has moved on a lot since then. Animator.js has now been incorporated into most of the major JavaScript frameworks, either by directly porting the code (Animator.js is released under a BSD license that allows people to do this) or by borrowing the techniques. In particular, CSS animations produce better results and use less processor power. For a modern library that exposes CSS animations through a similar API, I recommend jQuery.Transit.

I'm keeping this page up here for historical interest, because it's written in a tutorial style that will be appropriate if you want to learn how to create programatic animation in any language.

Thanks to Tim Stone, Kaspar Fischer, Clint Priest and other developers who contributed feedback and features.

Background and motivation

I've removed this section because it contained criticisms of other JavaScript libraries that were true in 2006, but not today. I also took the opportunity to rant on the topic of object-oriented inheritance, which was a topic I explored in greater length in the article Inheritance is Evil and Must Be Destroyed - Bernie Sumption, 2010

A better way of animating

An Animator is an object that generates a series of numbers between zero and one. Zero represents the start of the animation, one the end.

Check this out:

// This object controls the progress of the animation
ex1 = new Animator()
// the Animator's subjects define its behaviour
function updateButton(value) {
    var button = document.getElementById("ex1Button");
    button.innerHTML = "Progress: " + Math.round(value * 100) + "%";
// now click below: each click to the button calls ex1.toggle()

The Animator above was left with the default options, here's an example that uses more configuration:

ex2 = new Animator({
    duration: 1200,
    interval: 400,
    onComplete: function() {
        document.getElementById("ex2Target").innerHTML += "Bing! ";
function updateButton(value) {
    document.getElementById("ex2Target").innerHTML += " Badda ";

Animating element styles

Most of the time you want to animate one or more a style properties of an element. There are essentially only three kinds of CSS value - ones that scale numerically (like 10px), ones that scale with a RGB colour value(like #RRGGBB), and ones that don't scale (like bold / italic). Animator provides three utility classes for each of these kinds of properties, and between them they can animate any CSS style.

// animate margin-left from 0 to 100 px
ex3 = new Animator().addSubject(
    new NumericalStyleSubject(

// animate background-color from white to black
ex4 = new Animator().addSubject(
    new ColorStyleSubject(

// animating both - note how calls to addSubject() can be chained:
ex5 = new Animator()
        new NumericalStyleSubject(
        new ColorStyleSubject(
        new DiscreteStyleSubject(
            "ex5Button", "font-weight",
// also, check out the last subject, which causes font-weight to
//switch from normal to bold half way through the animation

If you've ever used moofx or scriptaculous then you are probably thinking that this is quite verbose, and you'd be right. Animator has a killer feature that removes the verbosity, but before we get to that, here are a couple more things you can do:

More complex effects

What if you have a number of elements that you want to animate in the same way? In that case, pass an array of elements into the Subject's constructor. There is no way to add and remove elements from a Subject after it has been constructed - if you want to do that, use one Subject for each element and use addSubject() and removeSubject() on the Animator.

// Applying the same effect to different elements is easy
ex6 = new Animator().addSubject(
    new NumericalStyleSubject(
        ["dot1", "dot2", "dot3"],

In previous examples, each subject has referred to the same element. This does not have to be the case:

// applying different effects to different elements is possible
ex7 = new Animator()
        new ColorStyleSubject(
        new NumericalStyleSubject(


Opacity gets special treatment. Since IE does not support the standard 'opacity' CSS style, NumericalStyleSubject will convert it into an appropriate filter.

ex8 = new Animator().addSubject(
    new NumericalStyleSubject(

Controlling the animation

When you click on a sample button in this article, you are calling toggle() on an animator object. There are a few more control functions:

  • play() plays the animation from the start to the end
  • stop() stops the animation at its current position
  • reverse() plays the animation in reverse
  • seekTo(pos) plays the animation from it's current position
  • seekFromTo(from, to)
seekFromTo(0.25, 0.75)

The benefit of using seekTo() is that it wil avoid sudden jumps in state when called half way through an animation:

this div uses play() and reverse on mouseover and mouseout
this div uses seekTo(1) and seekTo(0) on mouseover and mouseout


A transition is a function that takes a state (a number between 0 and 1) and returns another number between 0 and 1. This can be used to simulate acceleration, deceleration and more complex effects. You can pass in a transition to an Animator object's constructor using the cleverly named transition property.

The Animator.tx object provides a few ready made transitions:
  • Animator.tx.easeInOut is the default transition, and creates a smooth effect
  • Animator.tx.linear maintains a constant rate of animation
  • Animator.tx.easeIn starts slow, gets faster
  • Animator.tx.strongEaseIn exaggerated version of the above
  • Animator.tx.easeOut starts fast, gets slower
  • Animator.tx.strongEaseOut exaggerated version of the above
  • Animator.tx.elastic go slightly past the target point, then be drawn back
  • Animator.tx.veryElastic as above, but with an extra pass
  • Animator.tx.bouncy Hit the target point then bounce back
  • Animator.tx.veryBouncy as above, but with an extra 2 bounces

Sometimes you'll want to fine tune the above transitions. If you look at the source code where the Animator.tx object is created, you'll see that the above functions are all made by four factory functions:


// make a transition that gradually accelerates. pass in 1 for smooth
// gravitational acceleration, higher values for an exaggerated effect
ex9 = new Animator({
    transition: Animator.makeEaseIn(3),
    duration: 1000
    new NumericalStyleSubject(


// make a transition that, like an object with momentum being
// attracted to a target point, goes past the target then returns
ex10 = new Animator({
    transition: Animator.makeElastic(3),
    duration: 2000
    new NumericalStyleSubject(


// make a transition that, like a ball falling to floor, reaches
// the target and bounces back again
ex11 = new Animator({
    transition: Animator.makeBounce(3),
    duration: 2000
    new NumericalStyleSubject(


An Attack Decay Sustain Release envelope is a technique I lifted from music production. It is very useful for animations that start and end at the same value.

// This example shows you what an ADSR envelope looks like, but is
// otherwise useless the first three arguments are the boundary
// points of the 4 phases. The last is the sustain level.
// All should be between 0 and 1.
ex12 = new Animator({
    transition: Animator.makeADSR(0.25, 0.5, 0.75, 0.5),
    duration: 2000
    new NumericalStyleSubject(

A practical use of ADSR is to hold an animation in a certain state for a while, as in this yellow fade example

// This yellow fade is emphasised by holding it at full yellow
// for the first half of the animation
ex13= new Animator({
    transition: Animator.makeADSR(0, 0, 0.5, 1),
    duration: 1500
    new ColorStyleSubject(

Custom functions

Of course, you can write your own functions that do any kind of transition:

function setupEx14() {
    var wobbles = parseInt(prompt(
        "Enter a number of wobbles (try between 1 and 5)", ""));
    if (!wobbles) {
        alert("Sorry, I didn't understand that, have 2 wobbles.");
        wobbles = 2;
    // do some kind of crazy trigonometric stuff. I don't even
    // know what it all means, I just went crazy with the Math
    // functions
    ex14Tx = function(pos) {
        return ((-Math.cos(pos*Math.PI*((1+(2*wobbles))*pos))/2) + 0.5);
    ex14 = new Animator({
        transition: ex14Tx,
        duration: 2000
        new NumericalStyleSubject(


The killer feature

I wanted to explain how Animator works under the hood before I revealed this feature.

Like I said before, it's all a bit verbose at the moment, and most of the code in the above examples is just boilerplate. What we need is some kind of language that lets us define the style that we want to animate an object towards. Oh wait a second, we've already got one: CSS. A CSS style contains all the information we need to define an animation state:

ex15 = new Animator().addSubject(
    new CSSStyleSubject(
        "width: 12em; background-color: rgb(256, 256, 256); font-style: normal",
        "width: 40em; background-color: #F39; font-style: italic"));
// note how you can use any unit, not just 'px'.

CSSStyleSubject is a wrapper around the other three Subjects. It parses two CSS rule sets and for each property declaration, creates a NumericalStyleSubject if it looks like a number, or a ColorStyleSubject if it looks like a colour, or a DiscreteStyleSubject otherwise. DiscreteStyleSubjects are created with a threshold of 0.5, in other words the style changes from normal to italic half way through the animation.

Conveniently, you can also pass in CSS class names instead of rule sets:

ex16 = new Animator().addSubject(new CSSStyleSubject(
    "small white",
    "big blue bendy"));
// the classes small, big, white, blue and bendy are
// defined in this page's source.

When you're creating animations from CSS classes, it's easy to lose track of what your animator object is doing. The Animator.inspect() method returns a string that describes the animator:

This is pretty good, but we can still remove some more cruft. Most of the time, the element you want to animate will already be in its initial style. If this is the case, you can omit one of the rule sets and the initial state will be inferred from the elements current style. This uses getComputedStyle (or Element.currentStyle in IE) so reflects the element's actual style after applying CSS rules in style sheets.

ex17 = new Animator().addSubject(
    new CSSStyleSubject(
        "width: 300px; background-color: #F39"));

Finally, there is one last bit of syntactic sugar to make it easy to apply effects. The Animator.apply(element, style, options) function is a wrapper around creating a single CSSStyleSubject. The second argument is the style to fade to and the third is an optional set of constructor parameters for the Animator object. If you want to specify the full from and to styles, pass in a two item array as the second parameter.

ex18 = Animator.apply("ex18Button", "greenish"); // ta da!

Oh go on, one more feature...

By popular demand... Several people asked for an easy way to chain several animations together. AnimatorChain is an object that behaves a bit like an Animator, but wraps several other Animator objects and causes them to play in sequence.

var animators = [];
for (var i=0; i<3; i++) {
    animators[i] = Animator.apply("ex18blob-" + i), "blobEnd";
ex19 = new AnimatorChain(animators);
// the AnimatorChain object has toggle(), play(), reverse()
// and seekTo(state) functions just like Animator objects,
// so you can often use them where code expects an Animator

Well, that's it. Enjoy using Animator.js, and feel free to leave comments and feedback below.

Leave a Reply

Your email address will not be published. Required fields are marked *