January 28, 2007

Javascript Motion Tween

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

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() ).
The property that is updated on the target object, it can be empty ('')
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 value
End value
Animation duration in seconds
A string to append to the updated property ('%','pt','em' ...).
  • 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');
<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

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.

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

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()};

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

using the addListener method:

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' )

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.

[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');
tweenTA.onMotionChanged = function(event){
   myTA.value += event.target._pos + '\n';

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');
tweenTA2.onMotionChanged = function(event){
   myTA2.value = myText.substr(0,event.target._pos);

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.

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);


[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.onMotionFinished = undefined;

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.
var opacityTween = new OpacityTween(Object,easing,startOpacity,endOpacity,duration);


[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);

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.

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.

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

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

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'));

Open example in a new window



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)


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


Anonymous bakman said...

This is really superb work!

Is there a way to start multiple tweens in parallel ?

9:57 PM  
Blogger pim said...

Yes look at the example in TextTween it is using a class called Parallel, that you can download :)

11:28 PM  
Blogger Tek said...

Great work. I love the text completion motion idea ;)

10:45 AM  
Anonymous Paul said...

Philippe, This is really very impressive work -- very well written. There isn't any copyright/licensing information in the code. Were you intending to make this public domain?

Also, on your *.js links (near the bottom of the page) you have TextTween.js listed twice (one of them actually links to Sequence.js).

1:01 PM  
Blogger pim said...

Thanks for the positive comments.
About copyright or public domain, I have no idea on that matter.
I did write these because I was learning Javascript .. hrm let's say for fun, and I thought it would be a good exercise/experiment, actualy I never really used it for production, my main occupation involves Coldfusion and Actionscript :D but I thought other people might be interested.
If you have any suggestion, do not hesitate to let me know.

7:16 PM  
Anonymous Anonymous said...

The size sequence animation almost made me piss my pants.

1:31 PM  
Anonymous Anonymous said...

Curses.. I spent ages working on my own version of something similar.


(Just log on as a guest with no password, or regiter a new user.

Use cursor kets to move, but try dragging and dropping an object.)

I have dabbled in JS motion for quite a while http://gcyp.sa.gov.au
(sit and watch the clouds roll by.. and click on apples etc..)

The touble I have always had with other peoples 'modules' is they always contain more wizbangery than I need in one app.. and it feels like a waste of space having all these wonderful features I dont need still being loaded and processed just in case. (the old 20:80 rule).. so I always end up rolling my own.

Nice work!

from wolis (wm at wolispace dot com)

PS check out my Creative Object World (cow) if you have a spare moment http://wolispace.com/cow

2:10 PM  
Anonymous Anonymous said...

Awesome work!

I did something simelar to this but not as pretty and structured as this. Thanks!

4:45 PM  
Blogger pim said...

I tried moving a div whit it on my PSP and it worked pretty well :))

5:52 PM  
Anonymous Anonymous said...

Small type on first example: "t1 = new tween" - needs Capital T.

Great scripts though!

1:44 AM  
Anonymous Matt said...

This is GREAT!

The sequence class is amazing. It looks like you've thought of everything.

Everything I know about scripting I learned from actionscript and so this javascript was really easy for me to pick up on.

There are some other animation types like expoOut I'd like to see but I'm gonna take a look at it later today and see if I can't add my own to on top of your code.

Again thanks so much for this. It's awesome.

5:40 PM  
Anonymous Paul said...

Philippe, you've probably had several 1000 people grab a copy of your code by now. The copyright issue is still unresolved, though. If you intended to let people use your code then you should look into at least specifying how they are able to do that. I'd suggest you look at Creative Commons (http://creativecommons.org/about/licenses) as they have a variety of license types you can use easily.

As I said a few days ago, this is really impressive. I'm glad to see you've received some well deserved attention.

11:40 AM  
Anonymous Michal Hantl said...

Great work!

10:35 AM  
Anonymous cody lindley said...

Great work, thank you for sharing it.

4:54 PM  
Anonymous Diederik Van Durme said...

Thanx a lot. Just what I was looking for. Now with all the Ajax on its way, this is one 'very' usefull set of js files.

dank u, merci bien

9:06 AM  
Blogger Sholom said...

What I don't get is why this is needed?
Why not just use a gui to build this type of motion?

6:40 PM  
Anonymous Anonymous said...

Hi. Very useful. Thanks a lot. Please release it in the public domain or GPL. We want to use it for a nice web application. Free software !


7:56 PM  
Blogger pim said...

Thanks to Alexandre for helping me with this.
I have added the following in the the .js files headers:

Open source under the BSD License.
Copyright (c) 2001 Robert Penner
JavaScript version copyright (C) 2006 by Philippe Maegerman
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
* Neither the name of the author nor the names of contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.



10:02 AM  
Anonymous barry said...

This is completley brilliant. EXCELLENT job. My only issue however, is it not possible to tween to negative values?

This works:
new Tween(document.getElementById('img_holder').style, 'top', Tween.elasticEaseOut, 0, 100, 4, 'px'); t1.start();

This doesnt:
new Tween(document.getElementById('img_holder').style, 'top', Tween.elasticEaseOut, 0, -100, 4, 'px'); t1.start();

Tween to -100.... ideas?

7:21 PM  
Anonymous barry said...

Ach the negative value thing I just mentioned seems to be a bug in Sfari specifically, Firefox seems to work fine....

7:26 PM  
Anonymous Azer Koçulu said...

Very Good work, i like it..

8:53 AM  
Blogger familiarcat said...

Quite amazing. I'm stoked to see you got your easing equasions from Robert Penner. I'm a big fan of his work on Flash... but with Ajax coming down the pipe, this will bring a great asset to the web dev community. Thanks again!

10:30 PM  
Anonymous complexodus said...

This code is 100% pure love. You are a great man!!!

One thing I'm running into is when I use the Tween on a div that has text some bold text comes out pixelated. I'm doing a fade-in while tweening the height of a div. I've taken out the Tween and left the OpacityTween and it doesn't pixelate the text.

Interesting.... if you have time let me know what you think it might be.

10:16 AM  
Blogger Peaches said...

JSTween is really something else. I have a ton of experience with MCTween in ActionScript and my latest client decided they didn't want their homepage done in Flash, but still insisted on several Flash features.

JSTween was incredibly easy to use. At the moment I'm having an issue with it taking a TON of CPU resources though.

In this case I'm just moving a DIV with an image in it when you mouse over it.

var moving = false;
var position = 0;
var duration = 0;
var t1 = null;
var isOver = false;

function slideCard() {
if(!moving) {
t1 = new Tween(document.getElementById('card').style,'top',Tween.strongEaseOut,parseInt(document.getElementById('card').style.top),position,duration,'px');
delete t1.onMotionFinished;
t1.onMotionFinished = onFinishedShowHide;
t1.onMotionStarted = function() { moving = true;}

function hideCard() {
isOver = false;
position = 325;
duration = .3;
function showCard() {
isOver = true;
position = 190;
duration = .4;

function onFinishedShowHide() {
moving = false;
if(!isOver) {
else {

Anyone have any ideas?

9:54 PM  
Anonymous kyrie said...


any way to declare the constructors inside the html of a php file? err..
im making links of uncertain number of obejcts (wordpress listing posts) so it lists it by PHP, so i include javascript (by having it echoed in PHP) in between the loop enumerating the links, so for every link, there'd be a colortween object constructed. however, it says that the object is null...

i look at the page source and it did what it supposed to do- well it inserted a javascript in the middle of the code (in the body) and all. how come the variable isn't defined? is it because it was used outside the script? then how can i make the variable declared (used in the cosntructor) within the javascript be used outside it? argh... am dizzy...

8:07 PM  
Anonymous kyrie said...

can we have the color tween work on all links? i used it as a mouseover, changing the color property of the object.. but i can't make a contructor for each link item.. so maybe it can be tweaked to work for all "a href" objects?

12:55 AM  
Blogger pim said...

try this:
<script language="javaScript">
window.onload = function(){
var l = document.getElementsByTagName("a");
for(var i = 0; i < l.length; i++){
l[i].onmouseover = function(){
var i = new ColorTween(this.style,'color','','0000FF','FF0000',1)
l[i].onmouseout = function(){
var i = new ColorTween(this.style,'color','','FF0000','0000FF',1)

11:09 AM  
Anonymous kyrie said...

pim, it won't work... http://sunshadow.info/index.php (check the menu items)

3:23 PM  
Blogger pim said...

It seems to work, I see fade-in fade-out on your menu items when I mouse Over/Out

9:01 AM  
Anonymous Anonymous said...

Really nice work, much easier to understand than script.aculo.us or moo.fx.

One request would be a delay, so when you add lots of tweens in paralell they would all start at slightly different times. You could get some very interesting cascade effects with that.


10:34 PM  
Anonymous Russell Quinn said...

The tweening equations work by modifying the inline styles, but once the tween is complete they leave the final inline styles in tact. This might prove a problem if you are using external style sheets.

For example. I have a div that changes the background color on mouse hover. When the div is clicked then i perform a color tween, but once the tween is complete the hover effect no longer works because of the remaining inline style.

This example case can be fixed by:

colTween.onMotionFinished = function()
{ this.targetObject.backgroundColor = '';

11:17 AM  
Anonymous Anonymous said...

I wanted to thank you for putting this together. I've been programming in Actionscript for the last 5 years and have been using the tween classes for quite sometime and I have to tell you that this is the simplest and most effective presentation of JavaScript tweening I have ever seen. We run a site that auto generate flash websites for thousands of clients yet we built the complicated administration area that runs the whole show in Html/CF/Javascript/Css for the simplicity of quicker development time. We are in the process of building our version 2 admin which is pretty much AJAX run and I have been looking for a simple solution to the DHTML tweening trickery I wanted to use to give it that extra WOW factor. Well you hit it right on the money. Instead of tearing apart Yahoo and Googles JS ancd CSS pages to deduce what they are doing you hand over this incredible Tween Class. Jeeze, when people find out how easy it is to manipulate divs and graphics now it really could change the nature of how we look at building RIAs and sites outside of flash.

Also a couple other notes:
1) Some may flog me for this but I honestly would say you can make a bit of cash with this. I myself would gladly pay you a donation for the time and effort you put into this. If you can put a paypal donation link or something on the site I think you would get some good response. I would pay you $50 to $100 bucks right away just for the hours you saved (and will save) me in development.
2) Because of the diverse nature of our clients we have created an extensive hotbed for testing so I tested a few of the AJAX tweens I created on a few platforms and browsers (and multiple versions) and have found no errors yet. The only weak link I have found can be created by the developer themselves if they get too complicated with sequenced tweens or make some tweens run too long. Processing power! But it was a minor issue which can be avoided by testing the tweens on slower machines (I find the same thing happening in flash sometimes as well).

Here is a list of the OSes and browsers tested:
FF and FF
IE 6 and IE 7
Opera 9
AOL 1.5001.7.1
NN 7.2 NN 8.1.2 (a bit sluggish on slow machines)

OS – Vista
IE 7 FF 2

OS – Mac OSX (10.4.8) Leopard
Safari 2.0.4
NN 7.2

OS – Mac OSX (10.3.9) Jaguar
Safari 1.3.2
NN 7.1

I don’t really care about Opera since I see lots of bugginess in it all the time but it also seemed to work in it on winXP.

I thought I would give you the above list as a thanks since not everyone has the luxury of having that many OSes and browsers available to them to test. Time consuming but it pays off in the end by minimizing tech support on browser “funkiness” related issues.

So again thank you very much. I’ll keep checking into your blog to see new updates/comments/tweaks.

Have a great day.

Warren H

2:58 AM  
Blogger gourlay said...

Is there a way to use this package to do a non-linear tween. I want an object to follow a curved path. Thanks.

12:22 AM  
Anonymous Anonymous said...

I love this and it is pretty easy to set up. Thank you!

My only question is, is it possible to get it to work on style.display to show and hide div areas? I've played with a few things and I can't get it to work as is. I can simulate it by starting the div at height: 0 and opacity: 0 and then tweening the two but that doesn't work across the board.

8:53 PM  
Anonymous Anonymous said...

Hi pim,
I use your great code a lot, congrats, good good job!
Ive just tried opacityTween, and I found a bug in IE6.
Changing the IE specific line in the opacityTween.js to
if(t.filters) t.style['filter']='alpha(opacity = '+v+')';
does the job.

Mihaly K

4:34 PM  
Anonymous Jarno Rossi said...

OpacityTween generates a notice on firefox, because we have to use 'alpha' for IE

I've resolve that, using in OpacityTween the code used in ByteFx, in function bytefx.alpha. Tanx 2 Andr3a!

in this way it is perfect!

4:46 PM  
Blogger jarnoo said...

sorry...Im Jarno again.

Width Bytefx code we dont need the 'filter:Alpha(opacity=100);' for IE but a simple 'width'

for the notice in FF the problem is the value of 'v'.

however this works:

OpacityTween.prototype = new Tween();
OpacityTween.prototype.constructor = Tween;
OpacityTween.superclass = Tween.prototype;

function OpacityTween(obj,func,fromOpacity,toOpacity,duration){
this.targetObject = obj;
this.init(new Object(),'x',func,fromOpacity,toOpacity,duration);
var o = OpacityTween.prototype;
o.targetObject = {};
o.onMotionChanged = function(evt){
var v = Math.round(evt.target._pos);
var t = this.targetObject.style;
t.opacity = (v / 100);
t.MozOpacity = (v / 100);
t.KhtmlOpacity = (v / 100);
t.filter = "alpha(opacity=" + v + ")";

5:44 PM  
Anonymous Ed said...

Is it possible to use the tween class to move the scrollbar? If yes, how?

THank you.

11:30 PM  
Anonymous Corty McAlligan said...

It`s simply...



1:57 AM  
Blogger Vinodh said...

Its awesome...

8:41 PM  
Blogger Ricardo said...

I have noticed on the moveSquare example, it will not work without inline styling, there is a way to get it to work with import, link href, inline style sheet and inline styles, view the source here :

no spam popups or ads at my site.

8:55 PM  
Anonymous Microdesign said...

Thanks, these scripts are really awesome. The web1.0 era is officially over :P

9:44 AM  
Blogger phpdiscovery said...

Fixed IE 6's Fade :) using this:

o.onMotionChanged = function(evt){
var v = evt.target._pos;
var t = this.targetObject;
t.style['opacity'] = v / 100;
t.style['-moz-opacity'] = v / 100;
t.style.filter = "alpha(style=0,opacity:" + v + ")";

6:08 AM  
Blogger Кирилл said...

Ни хуя так... пиздатенько

5:20 PM  
Anonymous Steve Skyles said...

Hi Philippe and everyone,

I've made a tiny modification to tween.js that allows for the following...

t1 = new Tween(document.getElementById('photo').style, 'backgroundPosition', Tween.elasticEaseOut, 0, 500, 4, '0px $px');

'$' in in the suffix will be replaced with the tween value.


t.setPosition = function(p){
this.prevPos = this._pos;
var a = this.suffixe != '' ? this.suffixe : '';
if(a.indexOf('$') == -1) this.obj[this.prop] = Math.round(p) + a;
a = a.replace('$', Math.round(p));
this.obj[this.prop] = a;
this._pos = p;


I made the modification to suit my own needs and thought that someone else may be interested in it.

By the way, your code is beautiful!


12:31 AM  
Blogger Nate said...

Is it possible to tween without easing?

3:51 PM  
Blogger pim said...

You can pass null instead of easing method

4:08 PM  
Blogger Nate said...

Thank you... this code is incredible!

4:18 PM  
Blogger jezamorano said...

Está interesante el trabajo dessarrollado, aunque una documentación en español no estaría nada de mal

8:38 PM  
Anonymous Anonymous said...

Can't seem to get OpacityTween to work in ie7... anyone else have this problem? I have tried the solutions listed here...none work for me.

7:57 PM  
Anonymous Q5 Grafisch Webdesign said...

This doesn't work for me.

I have Mac, Safari :(

Great article though

8:23 PM  
Anonymous Anonymous said...

Thanks for your work on this. Really great stuff. I was at the end of a long and hard day when I found this and it kept my at my computer for a few more hours!
Loved the size sequence especially!

6:47 PM  
Blogger Ricardo said...

Great work!

I have a doubt: can we have a simple linear fadeIn + fadeOut?

I'm trying but... :)

12:38 AM  
Blogger pim said...

Just pass null as easing function ;))

9:49 AM  
Blogger Ricardo said...


11:38 AM  
Anonymous knarz said...

Thank you for this very nice package!

Can anyone tell me whats wrong with this?:

var preflop = new Sequence();
var i;

for(i = 0; i == 10; i++)
var c = i.toString();
var holecards = document.getElementById( 'holecards' + c );
preflop.addChild( new OpacityTween( holecards, Tween.regularEaseIn, 5, 100, 1) );


11:31 PM  
Anonymous zenx said...

Hi! Great script.

IE-s alpha filter has a very weird and annoying bug: if it is turned on on an element, it cannot display the #02050a color (a dark tone close to black). So if the element has that background color, or the text has that color, it will display as white. What's even more annoying, is that it does this also with images that are children to the element! If you have #02050a colored pixels in your images, and any ie filter is turned on, these pixels display as white pixels.

I'm using the OpacityTween class, and modified it to overcome some of this: when I want the opacity to be 100, I turn off the filter completely. When I want to tween the opacity to any other value, I add the filter and set the value. So here's the modified version:

function OpacityTween(obj,func,fromOpacity,toOpacity,duration){
this.targetObject = obj;
this.init(new Object(),'x',func,fromOpacity,toOpacity,duration);
var o = OpacityTween.prototype;
o.targetObject = {};
o.onMotionChanged = function(evt){
var v = evt.target._pos;
var t = this.targetObject;
t.style['opacity'] = v / 100;
t.style['-moz-opacity'] = v / 100;
if(t.filters) {
if(!t.filters.alpha) {
t.style.filter = 'alpha(opacity=100)';
if (v != 100) {
t.filters.alpha['opacity'] = v;
} else t.style.removeAttribute('filter');

So this way, you DON'T add the filter declaration in the CSS, the tween will add it, when needed.
You also need to specifically use removeAttribute('filter') when you want to turn it off, and you want to keep using IE's cleartype font smoothing when opacity is 100. Setting the object.style.filter = '' to an empty string will overcome the #02050a color bug, but having the filter in there with even an empty string or null will still disable IE's cleartype.

8:51 PM  
Anonymous nick said...

Nice work! One possible simplification to the API would be to automatically start animating a tween object when it is created. Using this approach the user would simply create the tween(s) at the time when the animation should start, and need not call a start method.

Multiple tween objects created in the same code block would be automatically synchonized since setTimeout would not be called until the current block has completed. See www.gapjumper.com for an example of this approach.

6:38 PM  
Blogger Matt Pelham said...

Hey, great work with this Class, I'm using it in everything and avoiding flash now as much as I can! I had some ideas on making the class even stronger:

1. Create an advanced manager class that looks at attributes tweened and loads appropriate javascripts.

2. Allow tweening entire classes based on IDs and pseduo-classes. This would have to read the CSS tag and create a sequence based on the tweens. This means a:link would be sequenced and a:hover could be sequenced with graceful degradation of the script. (See sil's Smooth Scroll at http://www.kryogenix.org/code/browser/smoothscroll/).

3. This is in a similar vein to #2, but as far as I have seen with experimenting, there is no way to change attributes such as margin, clip, or padding. Margin and padding are easily overcome, but without a clip-left property, one cannot Tween the cropping of content without using overflow and advanced ids.

If you would like any help implementing these changes, I would be happy to assist.

Matt Pelham

3:52 AM  
Blogger pim said...

Thank you for sharing these ideas.
To be honest I don't think I'm going to spend more time on this code.
It was more an experiment than anything else, in my day to day work I'm developing server side with coldfusion, and don't spend time integrating/animating pages.
I would be super happy to pass the code to anyone who would like to bring it a step further :)

10:36 AM  
Blogger Matt Pelham said...

Hey Pim, I would be happy to keep updating it. I have found an amazing script called getAnchorPosition that I have modified to only use IDs and anything (not just Anchors). Later implementations will pass any required tags. You can locate it here: http://www.mattkruse.com/javascript/anchorposition/source.html. With this and small modifications, all animations can target relative attributes.

In short, you can do advanced rollovers that do not overwrite themselves with a new tween (similar to yoyo() but for the entire animation). Each object reads its current x and y and moves directly to the end paramaters, tweening from the dynamic position.

Great work, I will be using this package for a long time.

7:53 PM  
Blogger atner said...

Great job!

12:02 AM  
Blogger Mark said...

Congratulations! This is great work..

The only problem I am finding is when using OpacityTween on a [div] without specifying the width or height of the div in IE6/7. In Firefox it works fine.

It simply doesn't work in IE6 / 7 on a div which hasn't got any width or height specified.

Anybody got the same problem or has a fix?

6:47 PM  
Anonymous SVA Search said...

That's pretty intense what you've done ! Awesome...

11:14 PM  
Blogger MarkSeo999 said...

Great work !

10:15 AM  
Anonymous Anonymous said...

Can the script motion tween between two pictures (jpeg) like flash does. If yes,can you provide me some guidance. Thanks,

6:37 PM  
Blogger pim said...

You might place the pictures on top of each other and tween their opacity.

6:44 PM  
Blogger Rupin Chheda said...

This work is great..Iam currently using your code in one of my websites,still to go public.
I have tried to minify all the files with JSMIN that I have downloaded,but I sometimes find errors in them.
Could you please do the same procedure and set them for download?

12:44 PM  
Anonymous Anonymous said...

Thanks for your reply to the question
"Can the script motion tween between two pictures (jpeg) like flash does. If yes,can you provide me some guidance."

It did work as you suggested but I do have a problem. During the second iteration, when the second images fades out, the first image does not appear(or kind of appears white). I believe I have to reset the opacity and visibility back for the first image. Although I try that it still shows some problem

3:16 PM  
Blogger pim said...

Could you point to something visible, so I can have a look ?

3:21 PM  
Anonymous ubh said...

Using the opacity tween on a splash/loading screen before entering my site, problem is that after the opacity tween has finished(100-0) I want to delete the splash screen (div box). However no browsers can seem to find any element that's been through a tween process. Anyone else had this problem as well?

6:36 PM  
Anonymous WORMSS said...

Hello, Love your code, I am a little confused with some of it though.
You have getPosition, getDuration, getTime but you have spelt getFinish wrong, you have put geFinish, I'm Just confused that I am the only one who has commented on it..
Great work. I have had a few problems with it, like telling it to go from 'currentDivHight' to 200, with a bounce over 2 seconds would have it hit 200, bounce a little, nearly stop at 200, but at the very very end, it would jump all the way to 1854px. I have not been able to fix that problem, But I have worked around it to an extent.

12:19 AM  
Blogger Charles Lowell said...

For those interested

I've created build to slurp all of the tweening components into a single file that does not pollute the global namespace, and also generates a minified version to save space.


10:31 PM  
Anonymous DuyNgn said...

For what it's worth, I've extended this Tween library to handle scaling as well. I basically work off pim's opacity script. Simply save the following code into a .js file(ScalingTween.js). Usage is the same as every other Tween class. Supports % and px.

Here's the code:

ScalingTween.prototype = new Tween();
ScalingTween.prototype.constructor = Tween;
ScalingTween.superclass = Tween.prototype;

function ScalingTween(obj,func,fromScale,toScale,duration,suffix){
this.targetObject = obj;
this.init(new Object(),'x',func,fromScale,toScale,duration,suffix);
var o = ScalingTween.prototype;
o.targetObject = {};
o.onMotionChanged = function(evt){
var v = evt.target._pos;
var t = this.targetObject;
t.style['width'] = v+this.suffixe;

2:28 AM  
Anonymous DuyNgn said...

It seems the post failed to capture the whole code...

The function line should read:

function ScalingTween(obj,func,fromScale,

All on one line.

5:46 PM  
Anonymous Jesse Friedman said...

This is great, and it works very well. However I can't get it to tween a css property like 'margin-left'. I have a site where I'm trying to scroll a div that is wider than it's containing div. By positioning relative it breaks it out in IE7.

Any ideas?

7:07 PM  
Blogger pim said...

have you tried div.style.marginLeft ?

12:34 PM  
Anonymous website design New York City said...

nice post

7:04 AM  
Anonymous AD said...

I have been looking for this for I dont know how long. Thank you very very very much for doing this and letting people use it for free. Great GREAT work.

4:10 AM  
Anonymous Anonymous said...

This work is excellent! The code is very well written and documented; the functionality provided is great. It was also very nice of you to share your code. Good job!

11:03 PM  
Anonymous Kevin said...

wow. I must say im impressed.. I'm also very very good at actionscript, also very familiar with the AS tweener class and also Fuse.. But i must say i never got the idea of converting this into JS. Hats Off man..

P.S: You somehow made me jealouse :P

Good Luck with your futur projects..

Kevin from mauritius.

8:25 PM  
Anonymous luminarious said...


I'm trying to learn game programming with javascript and despite the huge number of available frameworks, I still feel yours is best-suited for my purposes.

I use it in combination with http://code.google.com/p/vxjs/ and this gives me an ultra-lightweight framework (15KB), which seems speedy enough.

Thank you!

1:57 PM  
Anonymous Al said...

Great stuff! I have also converted Robert's Flash easing to a Javascript animation framework I built called "The Burst Engine".

Here's an example if you're interested in seeing it in action:
Ococat needs No Flash!

5:02 AM  
Blogger Ryan said...

Thanks for this AMAZING js man, exactly what I have been looking for!

one thing: anyone have an idea of the best way to make a colour tween that goes from say green -> blue -> red and then back again? ie. 3 colours?

2:20 PM  
Blogger Vlad Zinculescu said...

Congratulations! It's super great! But I have a problem in Mozilla with this stuff: http://bshop.itprofessionals.ro/newstileAdmin/

I press the it-pro dude and when the menu comes down it makes a funny effect on the div above.

If you could please help it will be super because I'm struggling for the past 2 days and couldn't find a solution.

11:15 AM  
Anonymous Anonymous said...

It looks like tweening percentages is a no-go. For example:

new Tween(document.getElementById(tmpID).style,"height",Tween.regularEaseIn,0,100,5,'%');

The action is executed but in under 1 second.

I need to use this because I don't know the height of each div.

Any ideas on how to fix this?

8:16 PM  
Blogger pim said...

I think you need to declare your element with % in advance, also maybe % accepts only rounded values ....

8:56 AM  
Anonymous noobhi said...

i have a problem, im kind of new with javascript and webscripting. anyway, i want to make a simple button move on mouseover without using flash. i tried using the the code it works when i copy paste it but when i try to use it on mybutton it doesnt work. does it only work on divs? can anybody enlighten me..
here's what im trying to do basically
td class="etst" onclick="t1 = new Tween(document.getElementById(this).style,'left',Tween.elasticEaseOut,0,500,4,'px');

im trying to learn the code first.. and i just cant get this to work.. =(

please go easy on me.. im still new and learning. thanks

9:12 AM  
Blogger pim said...

Maybe because your element doesn't have any ID.
Try give it an ID and if it doesn't work with getElementById(this), provide the ID explicitely : getElementById('realID')

9:37 AM  
Anonymous Anonymous said...

hey.. i've got a basic question.
how do i make the motiontween finish first before it rewinds..?

this is what i did,

onmouseover=start tween onmouseoff= rewind tween

the problem with this is if i mouseover the div at a certain point it keeps repeating the tween. how do i avoid this error?

6:10 AM  
Anonymous maheshchari said...

This is realy good examples and hard work,
thank you

7:15 AM  
Anonymous BRWebmaster said...

Fantastic job! But I have an issue here with IE8: I can't control the height of the object. Its always minimum 15px, I can't change it to 8px. For example this code:

t1.addChild(new Tween(elem.style,'width',Tween.bounceEaseOut,10,100,0.5,'px'));

div id="sq1" class="square bgRed" style="width:100px;height:8px;">

In Safari, works fine, the height changes to 8px, but in IE remains in 15px.

Any ideas?
Thank you for the code and the hard work.

5:08 PM  
Blogger Eduard said...

Thank you pim, really nice work!

Anyway, I found a bug in IE7 and IE8 at least. It's about the opacity tween. If there is another div with the style position:realtive inside the div you are changing opacity, the second div will not animate.

You can try it reaplacing the code in your example post, and you will see div 'insideSquare33' will be 100 of opacity since start. In FF an others browsers it works ok.

(note: i removed "<" characters to post the code.

div id="square33" style="width:50px;height:50px;background-color:#FF0000;filter:Alpha(opacity=100);position:relative;">div id="insideSquare33" style="height:20px;background:blue;position:relative;">/div/div

Any solution?

Thank you!!

1:27 PM  
Blogger pim said...

Unfortunately I don't have time to spend on this right now :( I hope you will find a quick solution to your problem ...

1:31 PM  
Blogger Director said...

Sweet Site. I linked to your blog. Great examples and awesome clean coding. Thanks for your efforts.

3:11 AM  
Anonymous Anonymous said...

The examples are very nice and super.
Gud work keep it up.

8:29 AM  
Anonymous Flash2nd said...

this is awesome stuff, thanks!

11:02 PM  
Anonymous Heleh Hunt said...


I will try it. Thanks. I am joining as your followers.

2:29 PM  
Blogger C said...

U are the Man !!! Hats Off to you...
With this potential i guess u must have a website of ur own and not under any blogger !!! Seriously i call the king of Tweens !!!

8:37 PM  
Anonymous Nabil said...

When was the last update please?

3:55 AM  
Anonymous Rodrigo Silveira said...

Awesome work! Thanks!

6:23 PM  
Anonymous Anonymous said...

Excellent work! I've always wanted to see Action script style easing replicated in Javascript.
Thanks for sharing :)

10:40 AM  
Blogger necdet said...

Hi pim,

Firstly thanks for your script and thanks for sharing it.

If you have time, i need a little advice from you.
I want to implement background effect with whenever you move the mouse to a direction, the background image will move with the mouse with a strongEaseOut effect.

I am trying to use ,
background-poisiton: val val for implementing the animation.

Now, i want to use Tween to add strongEaseOut effect. But it seems, in Tween, the value of the style you want to change in time, is a single value.

I tr to use,
but it isn't supported by many browser.

Do you have an advice?
Or maybe it is not the way of doing this, with Tween.

many thanks.

1:43 PM  
Blogger pim said...

Try backgroundPosition

7:27 PM  
Anonymous Tristan said...

This is exactly what I was looking for.Really great work.
I'm sorry I can't yet make this great zooming out of your screen...


7:48 PM  
Anonymous search engine optimization melbourne said...

Nice blog sharing.but Can't seem to get OpacityTween to work in ie7... anyone else have this problem? I have tried the solutions listed here...none work for me.

10:23 AM  

Post a Comment

<< Home