January 28, 2007

Javascript Motion Tween



The Tween class
CONSTRUCTOR
var t = new Tween(object,property,easing,start,end,duration,suffixe);

object:
type:Object
The object you want to modify. It can be any object, a visual object that you want to animate ( document.body.style ) or an anymous object ( new Object() ).
property:
type:String
The property that is updated on the target object, it can be empty ('')
easing:
type:Function
The easing that will be applied to motion. ( I have listed the functions below and created a sample to allow you to try them )
start:
type:Number
Start value
end:
type:Number
End value
duration:
type:Number
Animation duration in seconds
suffixe:
type:String
A string to append to the updated property ('%','pt','em' ...).
METHODS
  • start()
  • rewind()
  • fforward()
  • stop()
  • resume()
  • continueTo( end, duration )
  • yoyo()
  • addListener( listenerObject )
  • removeListener( listenerObject )




<div id="sq" style="width:50px;height:50px;position:relative;left:0px;border:1px solid #333333;"></div>
<input type="button" value="start()" onclick="
t1 = new Tween(document.getElementById('sq').style,'left',Tween.elasticEaseOut,0,500,4,'px');
t1.start();">
<input type="button" onclick="t1.stop();" value="stop()">
<input type="button" onclick="t1.resume();" value="resume()">
<input type="button" onclick="t1.rewind();" value="rewind()">
<input type="button" onclick="t1.fforward();" value="fforward()">


Easing functions
About Easing Classes and Methods
The default easing functions are methods of the Tween.as class.
  • Tween.regularEaseIn
  • Tween.regularEaseOut
  • Tween.regularEaseInOut
  • Tween.strongEaseIn
  • Tween.strongEaseOut
  • Tween.strongEaseInOut
  • Tween.backEaseOut
  • Tween.backEaseIn
  • Tween.backEaseInOut
  • Tween.bounceEaseOut
  • Tween.bounceEaseIn
  • Tween.bounceEaseInOut
  • Tween.elasticEaseIn
  • Tween.elasticEaseOut
  • Tween.elasticEaseInOut
A sample to try these methods

EVENTS AND LISTENERS
onMotionStarted( eventObject )
onMotionChanged( eventObject )
onMotionFinished( eventObject )
onMotionStopped( eventObject )
onMotionLooped( eventObject )
onMotionResumed( eventObject )

the eventObject passed contains 2 properties:
  • target : the Tween instance (object)
  • type : the event name (string, ex: 'onMotionChanged')


2 ways to use events :

adding a method on your Tween instance with the same name as the event you want to listen.

Example:
t1A = new Tween(document.getElementById('sqA').style,'left',Tween.elasticEaseOut,0,500,1,'px');
t1A.onMotionFinished = function(){alert( 'onMotionFinished' )};
t1A.start();



Example:
using the yoyo() method, the following code will create an endless animation:
t1C = new Tween(document.getElementById('sqC').style,'left',Tween.elasticEaseOut,0,500,1,'px');
t1C.onMotionFinished = function(){this.yoyo()};
t1C.start();



If, for example you wanted the yoyo() to perform only once, you would write code like
t1C.onMotionFinished = function(){
   this.yoyo();
   this.onMotionFinished = undefined;
}

using the addListener method:

Example:
t1A = new Tween(document.getElementById('sqA').style,'left',Tween.elasticEaseOut,0,500,1,'px');
var a = new Object();
a.onMotionFinished = function(){
   alert( 'onMotionFinished' )
};
a.onMotionStarted = function(){
   alert( 'onMotionStarted' )
}
t1A.addListener(a)
t1A.start();




The advantage of this is that you can add as many listeners as desired.
If you want to remove a listener, you can use the method 'removeListener( listenerObject )', where the listenerObject is the reference to the object that was added as listener.

Because we are tweening values, it is possible to instantiate a tween that won't directly apply changes to a visual object.

Example:
[textarea id="myTA" cols="40" rows="10"][/textarea]

[input type="button" value="tween from 1 to 100" onClick="
tweenTA = new Tween(new Object(),'xyz',Tween.bounceEaseOut,1,100,1);
var myTA = document.getElementById('myTA');
myTA.value='';
tweenTA.onMotionChanged = function(event){
   myTA.value += event.target._pos + '\n';
};
tweenTA.start();"]




Same example, but more 'creative':

[textarea id="myTA2" cols="40" rows="8"][/textarea]

[input type="button" value="tween text" onClick="
myText='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
tweenTA2 = new Tween(new Object(),'xyz',Tween.bounceEaseOut,0,myText.length,3);
var myTA2 = document.getElementById('myTA2');
myTA2.value='';
tweenTA2.onMotionChanged = function(event){
   myTA2.value = myText.substr(0,event.target._pos);
};
tweenTA2.start();"]




The ColorTween class
ColorTween.js extends the Tween.js class, its purpose is to manage transitions between two colors.
Because it is a subclass of Tween you must include the Tween.as class before you include the ColorTween.js class.

[script language="javascript" src="Tween.js"][/script]
[script language="javascript" src="ColorTween.js"][/script]

Because ColorTween.js is a subclass of Tween.js, all the Tween methods and events are available.

CONSTRUCTOR
var colorTween = new ColorTween(object,property,easing,startColor,endColor,duration);

An example will be worth a thousand words:

[div id="square22" style="width:50px;height:50px;background-color:#FF0000;"][/div]
[input type="button" value="toggle Color (red-blue)" onClick="
colorTween = new ColorTween(document.getElementById('square22').style, 'backgroundColor', Tween.bounceEaseOut, 'FF0000', '0000FF', 3);
colorTween.start()"]





Example:

[input type="button" value="Click to animate the background color of this page" onclick="
bgTween = new ColorTween(document.body.style, 'backgroundColor', Tween.bounceEaseOut,'FFFFFF','000000',2);
bgTween.onMotionFinished = function(){
   this.yoyo();
   this.onMotionFinished = undefined;
};
bgTween.start();"]



Notice the code in bold, without it, the animation would play forever, which would be useful if we wanted to have an element that blinks or pulse. I'll let your imagination do the job.



The OpacityTween class
OpacityTween.js extends the Tween.js class, its purpose is to manage opacity transitions on visual objects.
Because it is a subclass of Tween you must include the Tween.as class before you include the OpacityTween.js class.

[script language="javascript" src="Tween.js"][/script]
[script language="javascript" src="OpacityTween.js"][/script]

Because OpacityTween.js is a subclass of Tween.js, all the Tween methods and events are available.
CONSTRUCTOR
var opacityTween = new OpacityTween(Object,easing,startOpacity,endOpacity,duration);

Example:

[div id="square33" style="width:50px;height:50px;background-color:#FF0000;filter:Alpha(opacity=100);"][/div]
[input type="button" value="change Opacity (100 - 0)" onClick="
opacityTween = new OpacityTween(document.getElementById('square33'),Tween.bounceEaseOut, 100, 0, 3);
opacityTween.start()"]




You will notice the use of 'filter:Alpha(opacity=100);' on the square div. If you don't add this, IE will will throw an error 'filter.alpha is null or not an object'.

The TextTween class
TextTween.js extends the Tween.js class, its purpose is to manage text effects.
Because it is a subclass of Tween you must include the Tween.as class before you include the TextTween.js class.

[script language="javascript" src="Tween.js"][/script]
[script language="javascript" src="TextTween.js"][/script]

Because TextTween.js is a subclass of Tween.js, all the Tween methods and events are available.

CONSTRUCTOR
var t = new TextTween(object,property,text,easing,duration);

Click here to see it in action.
I have added the interesting code below the example.

The Sequence class

The sequence.js class allows you to chain Tweens, it means that the Tweens that have been added via the 'addChild()' method will be executed in the sequence they have been added.
Besides, a Sequence can be a child of a Sequence, allowing you to build and reuse complex animations.

METHODS
  • addChild( Tween )
  • removeChild( Tween )
  • start()
  • rewind()
  • fforward()
  • stop()
  • resume()


EVENTS
onMotionStarted( eventObject )
onMotionFinished( eventObject )
onMotionStopped( eventObject )
onMotionLooped( eventObject )
onMotionResumed( eventObject )

Usage:
var my_seq = new Sequence();
my_seq.addChild(new Tween(elem1.style,'width',Tween.bounceEaseOut,25,100,0.5,'px'));
my_seq.addChild(new Tween(elem2.style,'width',Tween.bounceEaseOut,25,100,0.5,'px'));
my_seq.start()

Example:
Open example in a new window



http://jstween.sourceforge.net

Download
Tween.js
ColorTween.js
OpacityTween.js
TextTween.js
Sequence.js
Parallel.js

See it in action
Dock menu @ 2210media.com

Expandable textarea from Arturo Monterroso

PS: I would be glad to add other examples here, so if you did something with the tween class, do not hesitate to let me know (pim.man at gmail dot com)



References

This is the description of Flash's Tween class:

"The Tween class lets you use ActionScript to move, resize, and fade movie clips easily on the Stage by specifying a property of the target movie clip to be tween animated over a number of frames or seconds. The Tween class also lets you specify a variety of easing methods. Easing refers to gradual acceleration or deceleration during an animation, which helps your animations appear more realistic. For example, the options on a drop-down list component you create might gradually increase their speed near the beginning of an animation as the options appear, but slow down before the options come to a full stop at the end of the animation as the list is extended. Flash provides many easing methods that contain equations for this acceleration and deceleration, which change the easing animation accordingly.

The Tween class also invokes event handlers so your code may respond when an animation starts, stops, or resumes or increments its tweened property value. For example, you can start a second tweened animation when the first tween invokes its Tween.onMotionStopped event handler, indicating that the first tween has stopped."


Robert Penner
Using the Tween and Transition Classes in Flash MX 2004
Macromedia Flash