Writing Customized Scriptaculous Animators
September 29th, 2007
I recently had a need to animate an arbitrary value over time in javascript. Now script.aculo.us animates things quite well, but all the animation functions only manipulate things which directly change your website appearance. What if I want to write my own effect
For example, lets say I want to display a completion percentage. I simply want to display a number which goes from 0% to 100% over some period of time. Like this:
Since there is no canned scriptaculous effect to do this for us, we write our own. And its not even that hard thanks to prototype, and the scriptaculous class Effect.Base. Here is what it looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// Create a new class to hold our functionality Effect.WritePercent = Class.create(); // Extend our class with the effects base that all scriptaculous efects share Object.extend(Object.extend(Effect.WritePercent.prototype, Effect.Base.prototype), { // initialize() should setup any variables you will need while updating, // as well as setup options (and defaults) to be passed into the effects engine. initialize: function(element) { // Save the element to update internally to this object this.element = $(element); // Create an options hash based on some defaults, with the optional // options object merged into the defaults. var options = Object.extend({ from: 0.0, to: 1.0 }, arguments[1] || {}); // Everything is setup, kick off the animation this.start(options); }, // update() always receieves the "position" argument which contains the value // of the current frame of the animation. So put here the javascript that changes // the page on each frame. update: function(position) { //convert to a percentage var value = parseInt(position * 100) + '%'; // write the percentage to a div this.element.update(value); } }); |
I wont describe the details since its been heavily commented. You should be able to get the gist of it.
And so we invoke this the same we would any standard effect:1 2 3 4 5 6 7 8 |
new Effect.WritePercent('element_id_to_write_in'); // or with options new Effect.WritePercent('element_id_to_write_in', { from: 0.25, to: 0.75, duration: 3, transition: Effect.flicker }); |
There is lots more you can do with it, your imagination is really the limit. Also the Effect.Base class API allows for more functions, but I havent figured out what they all do yet. Check out the source of effects.js if you want to explore further the way custom work. But this should get you quite far for your highly customized animations.
Leave a Reply