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. Animator.js has served its purpose, and most people will be better served by a general purpose JavaScript framework: I recommend jQuery.
I'm keeping this page up here for historical interest, and because Animator.js may still be of interest to people who want a small, fast library that does animation and nothing else.
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 ex1.addSubject(updateButton); 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! "; } }) ex2.addSubject(updateButton); 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( "ex3Button", "margin-left", 0, 100));
// animate background-color from white to black ex4 = new Animator().addSubject( new ColorStyleSubject( "ex4Button", "background-color", "#FFFFFF", "#F4C"));
// animating both - note how calls to addSubject() can be chained: ex5 = new Animator() .addSubject( new NumericalStyleSubject( "ex5Button", "margin-left", 0, 100)) .addSubject( new ColorStyleSubject( "ex5Button", "background-color", "#FFFFFF", "#F4C")) .addSubject( new DiscreteStyleSubject( "ex5Button", "font-weight", "normal", "bold", 0.5)); // 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"], "margin-right", 10, 50));
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() .addSubject( new ColorStyleSubject( "ex5ButtonA", "background-color", "#FF9", "#9F9")) .addSubject( new NumericalStyleSubject( "ex5ButtonB", "padding", "5px", "15px"));
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( "ex8Button", "opacity", 1, 0.25));
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 endstop()stops the animation at its current positionreverse()plays the animation in reverseseekTo(pos)plays the animation from it's current positionseekFromTo(from, to)
play() |
0%
|
stop() |
|
reverse() |
|
seekTo(0.5) |
|
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:
Transitions
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.
Animator.tx.easeInOutis the default transition, and creates a smooth effectAnimator.tx.linearmaintains a constant rate of animationAnimator.tx.easeInstarts slow, gets fasterAnimator.tx.strongEaseInexaggerated version of the aboveAnimator.tx.easeOutstarts fast, gets slowerAnimator.tx.strongEaseOutexaggerated version of the aboveAnimator.tx.elasticgo slightly past the target point, then be drawn backAnimator.tx.veryElasticas above, but with an extra passAnimator.tx.bouncyHit the target point then bounce backAnimator.tx.veryBouncyas 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:
Animator.makeEaseIn()
// 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 }); ex9.addSubject( new NumericalStyleSubject( "ex9Button", "margin-left", 0, 200));
Animator.makeElastic()
// 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 }); ex10.addSubject( new NumericalStyleSubject( "ex10Button", "margin-left", 0, 200));
Animator.makeBounce()
// 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 }); ex11.addSubject( new NumericalStyleSubject( "ex11Button", "margin-left", 0, 200));
Animator.makeADSR()
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 }); ex12.addSubject( new NumericalStyleSubject( "ex12Button", 'margin-left', 0, 400));
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
});
ex13.addSubject(
new ColorStyleSubject(
"ex13Button",
"background-color",
"#FFFFFF",
"#FFFF00"));
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 }); ex14.addSubject( new NumericalStyleSubject( "ex14Button", "margin-left", 0, 100)); ex14.play(); };
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( "ex15Button", "width: 10em; 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( "ex16Button", "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( "ex17Button", "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.
Thanks for sharing your work with us! Your theme is just awesome!
[...]Thanks for sharing your work with us! Your theme is just awesome![...]
Yout animator.js code is wonderful for some main reasons:
1) It does only animations, that’s exactly what everyone mostly needs now days on the web.
No tons of lines of code to do everything like jQuery and Mootools, when we need only an easy way to animate a website.
2) The code is readable, it does not require scientists to understand the code, normal sw engineers can read it.
What’s up? Will you go on updating it and releasing more.
I read in post 56 that you are currently trying to make a version fro Flash, why is this? I’m asking because another good question in now days is do we give up javascript animation library to move all to Flash? Flash seems to me still to buggy, I don’t know what u think about it.
Thanks anyway so much for sharing such a nice clean and readable piece of code.
Cheers!
I just want to say two words: Great Job!
I hope you will develop this script. This can be very helpfull for everyone, even experienced programmmer.
Pingback: A Curious Animal » JavaScript animations: Why maths are important?
wooow thanks men, awsome job
Thanks again Bernie, this little library really helped me understand animation and a lot more about javascript. Let me know if you release anything else :)
Your animation library is one of the cleanest and most useful that I have encountered. I liked your example of chaining together animations.
The feature that I need is to be able to sync several animators together and play them concurrently not chained. The TimelineMax class by greensock provides this functionality for flash but I have yet to find a JS library that has this feature. It would be nice to animate several objects with different starting time offsets and control them using one timeline.
100% Agree with you. You rock man ….
Great stuff and very understandable code.
The only bad thing in this page for me is that pinky background that makes me narrow my eyes while read the text/code (which is very addictive as it becomes easier and more powerful). ;)
Great job!
Love to use it for many things! Thanks alot!!!
Thanks for sharing such a wonderful code, neat and clean. I am going to use it in one of my near project and will let you know.
Thanks buddy…….
This will deinately help to make my website appearance good
Just wanted to thank you for the animator.js
(It’s running on my website. Just discovered where it came from and thought I ought to say thanks.)
Thanks.
ps.It was incorporated into an website builder tool I used to first build my site. Have migrated to dreamweaver, figured out the js and still appreciate it’s simplicity
thanks very much for sharing wonderful code ,am using the script in my project .thank u so much…
this is absolutely best and most featured animation js library i’ve ever seen, THANK YOU VERY MUCH!!
I’m using this to animate some SVG (some SMIL’s DOM methods are missing in Webkit) and so far, the only thing I miss is the ability to pause an animation
Good idea – I’ve added a stop() method.
Nice, although I needed a pause/resume method, so I wrote them:
They work great for me :)
Pingback: A herança é má e deve ser destruída | Dalaz
Thanks heaps for this javascript library, it has all the mathematics I was looking for :)
I ported the concept idea to Delphi (Object Pascal), minus the CSS stuff.
I’m going to use the animation to make a smooth zoom in/out for a map in my application. It seems eye candy and animation is quite lacking in desktop programming..
IE9 : opacity bug fix
when
css)
xtag { opacity:1.0; -moz-opacity:1.0; -khtml-opacity:1.0; filter:alpha(opacity=100); }
js)
var animator = new Animator( { ‘duration’:150 })
.addSubject(new NumericalStyleSubject(obj_xtag, “opacity”, 1, 0));
patch)
[1st : line 45 : insert : _get_ie_ver]
Animator.prototype = {
_get_ie_ver:function(){
var version = 0; // we assume a sane browser
if (navigator.appVersion.indexOf(“MSIE”) != -1){
// bah, IE again, lets downgrade version number
version = parseFloat(navigator.appVersion.split(“MSIE”)[1]);
}
return version;
},
[2nd : line 258? : replace : if command]
// original code : if (property == ‘opacity’ && window.ActiveXObject) {
if (property == ‘opacity’ && window.ActiveXObject && this.ie_ver<9) { /* for IE9 BS */
this.property = 'filter';
LOVE YOUR WORK. I am creating a avatar chat where you can move your own avatar around and I was looking for how to smoothly move one image from point a to b using javacsript, you gave just that and more. Thanks!!!
Bernie, brother.
Thanks for giving us some inspiration.
I was wondering if anyone has or has seen a good gradient-colour-fade algorithm.
I pose this question cos I’ve been using RaphaelJS, and fading from one colour to a gradient it’s pretty ugly…nothing like Flash+AS3.
I’d love to find a way to help that Raphael to have that sorted; So why not asking around the Gurus first?
cheers ears
Otto
If it’s a simple linear gradient from two colours to two different colours, then in principle, you just fade both colours at the same time.
Animator.js gives you the primitives you need, but you’ll need to write some glue code. Create a new subject, called say GradientSubject. A subject is just an object with a setState method that takes one argument. See the docs in the download for how to add a subject to an Animator object.
As you run the Animator, this setState method will be called with a series of numbers between 0 and 1. I haven’t executed the following code and it’s far from complete (The problem of actually generating CSS for the gradient is left to you) but it should get you started.
Let me know if you get something working.
Bernie :o)
Thanks, I’ll see if I can get this in when I have some spare time :o)
hi bernie, thank you for this small but really useful library
I suggest to create a special “Subject” class to animate js properties
for example,
el.scrollTop
el.scrollLeft
thank you!
nevermind, I’ve read the code, this is excellent! thank you!
Hello,
First of all, thank you for sharing this great piece of code. It’s really useful when you’re stuck to not use jQuery or other library.
I’m quite new to programming and I have a problem that I don’t know how to solve. Maybe I’m doing something wrong.
So, if I have an animation that runs to the end, and after that I change from outside your code a property (like width) for that element, when the animation is seekTo(0) it doesn’t take into account the new width I set. Can you make your class take into account any changes when it is seekTo(0) or seekTo(1)?
Thank you very much again for this great class.
If you change the width from outside the Animator, you need to create a new Animator object to use seekTo/From with this new width.