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
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 :
1Щ 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;
}
2Щ 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
103 Comments:
This is really superb work!
Is there a way to start multiple tweens in parallel ?
Yes look at the example in TextTween it is using a class called Parallel, that you can download :)
Cheers,
Pim
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).
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.
Cheers
The size sequence animation almost made me piss my pants.
Curses.. I spent ages working on my own version of something similar.
http://wolispace.com/josh
(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
Awesome work!
I did something simelar to this but not as pretty and structured as this. Thanks!
Btw,
I tried moving a div whit it on my PSP and it worked pretty well :))
Small type on first example: "t1 = new tween" - needs Capital T.
Great scripts though!
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.
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.
Great work!
Great work, thank you for sharing it.
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
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 !
http://alexandre.quessy.net/
Thanks to Alexandre for helping me with this.
I have added the following in the the .js files headers:
/**********************************************************************
TERMS OF USE - EASING EQUATIONS
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
met:
* 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
distribution.
* 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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************/
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?
Ach the negative value thing I just mentioned seems to be a bug in Sfari specifically, Firefox seems to work fine....
Very Good work, i like it..
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.
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;}
t1.start();
}
}
function hideCard() {
isOver = false;
position = 325;
duration = .3;
slideCard();
}
function showCard() {
isOver = true;
position = 190;
duration = .4;
slideCard();
}
function onFinishedShowHide() {
moving = false;
if(!isOver) {
hideCard();
}
else {
showCard();
}
}
/***************************************************/
Anyone have any ideas?
I LUUUV YOU!!!!!!
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...
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?
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(){
alert(this.style.color)
var i = new ColorTween(this.style,'color','','0000FF','FF0000',1)
i.start()
}
l[i].onmouseout = function(){
var i = new ColorTween(this.style,'color','','FF0000','0000FF',1)
i.start()
}
}
}
</script>
pim, it won't work... http://sunshadow.info/index.php (check the menu items)
It seems to work, I see fade-in fade-out on your menu items when I mouse Over/Out
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.
monk.e.boy
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 = '';
};
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:
OS-WinXP
FF 1.5.0.10 and FF 2.0.0.2
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
FF 2.0.0.3
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
Is there a way to use this package to do a non-linear tween. I want an object to follow a curved path. Thanks.
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.
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.
Best,
Mihaly K
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!
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 + ")";
}
Is it possible to use the tween class to move the scrollbar? If yes, how?
THank you.
It`s simply...
FANTORGASMIHYPERTASTIC!!!111111
:)
Its awesome...
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 :
http://www.freewebs.com/gmn17/moveSquare.htm
no spam popups or ads at my site.
Thanks, these scripts are really awesome. The web1.0 era is officially over :P
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 + ")";
}
Ни хуя так... пиздатенько
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;
else{
a = a.replace('$', Math.round(p));
this.obj[this.prop] = a;
}
this._pos = p;
this.broadcastMessage('onMotionChanged',{target:this,type:'onMotionChanged'});
}
---------------------------
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!
Thanks
Is it possible to tween without easing?
You can pass null instead of easing method
Thank you... this code is incredible!
Está interesante el trabajo dessarrollado, aunque una documentación en español no estaría nada de mal
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.
This doesn't work for me.
I have Mac, Safari :(
Great article though
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!
Great work!
I have a doubt: can we have a simple linear fadeIn + fadeOut?
I'm trying but... :)
Just pass null as easing function ;))
Txs!
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) );
}
preflop.start();
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.
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.
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
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 :)
Regards,
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.
Great job!
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?
That's pretty intense what you've done ! Awesome...
Great work !
Can the script motion tween between two pictures (jpeg) like flash does. If yes,can you provide me some guidance. Thanks,
You might place the pictures on top of each other and tween their opacity.
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?
Thanks
Rupin
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
Could you point to something visible, so I can have a look ?
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?
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.
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.
http://github.com/cowboyd/tween/tree/master
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;
}
It seems the post failed to capture the whole code...
The function line should read:
function ScalingTween(obj,func,fromScale,
toScale,duration,suffix){
All on one line.
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?
have you tried div.style.marginLeft ?
nice post
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.
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!
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..
Cheers,
Kevin from mauritius.
Hi!
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!
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!
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?
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.
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?
I think you need to declare your element with % in advance, also maybe % accepts only rounded values ....
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');
t1.start();">
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
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')
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?
This is realy good examples and hard work,
thank you
Hi PIM
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.
BRWebmaster
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!!
Unfortunately I don't have time to spend on this right now :( I hope you will find a quick solution to your problem ...
Sweet Site. I linked to your blog. Great examples and awesome clean coding. Thanks for your efforts.
The examples are very nice and super.
Gud work keep it up.
http://javascriptfactory.blogspot.com
this is awesome stuff, thanks!
Thanks
I will try it. Thanks. I am joining as your followers.
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 !!!
When was the last update please?
Awesome work! Thanks!
Excellent work! I've always wanted to see Action script style easing replicated in Javascript.
Thanks for sharing :)
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,
background-position-x/y
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.
Try backgroundPosition
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...
Thanks!!!
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.
Post a Comment
<< Home