A Tween is the base class that all tweens are made of.
A Tween instance handles tweening one or more properties of any object (or array of objects) over time. Tweens can be used on its own or in conjunction with advanced sequencing tools like Timeline
s to make complex tasks much simpler. With scores of other animation frameworks to choose from, why consider the GreenSock Animation Platform?
- SPEED - The platform has been highly optimized for maximum performance. See some speed comparisons yourself in this demo
- Freakishly robust feature set - In addition to tweening any numeric property of any object, plugins can be activated to tween hex colors, beziers, CSS, plus LOTS more. It can round values, use relative values, smoothly
reverse()
on the fly, automatically detect and accommodate getter/setter functions, employ virtually any easing equation, ;pause()
andresume()
anytime, and intelligently manage conflicting tweens of the same object with various overwrite modes. - Sequencing, grouping, and management features - GSAP's timelines make it surprisingly simple to create complex sequences or groups of tweens that you can control as a whole.
play()
,pause()
,restart()
, orreverse()
. You can even tween a timeline'stime()
orprogress()
to fastforward or rewind the entire timeline. Add labels, change the timeline'stimeScale
, nest timelines within timelines, and much more. This can revolutionize your animation workflow, making it more modular and concise. - Ease of use - Designers and developers alike rave about how intuitive the platform is.
- Support and reliability - With frequent updates, dedicated forums, committed authorship, a solid track record, a proven funding mechanism, and a thriving community of users, the platform is a safe long-term bet (unlike many open source projects).
- Expandability - With its plugin architecture, you can activate as many (or as few) extra features as your project requires. Write your own plugin to handle particular special properties in custom ways. Minimize bloat and maximize performance.
Usage
The most common type of tween is a gsap.to()
tween which allows you to define the destination values:
var photo = document.getElementById("photo");
gsap.to(photo, {duration: 2, width: "200px", height: "150px"});
The above code will tween the width and height properties of the <img>
DOM element with an id of “photo” from whatever the current values are to 200 and 150 respectively over the course of 2 seconds. Notice the width and height values are defined inside a generic object (between curly braces). Put as many properties there as you want.
If you pass a string (text) into a tween as the target (like gsap.to("#myID", {duration: 1, left: "100px"})
) GSAP will use a selector engine (jQuery if present, or document.querySelectorAll()
or lastly, document.getElementById()
(automatically removing the “#” prefix if it’s there)).
So once GSAP is loaded, you can easily animate things like this:
//tween the element with ID of "myID"
gsap.to("#myID", {duration: 2, backgroundColor: "#ff0000", width: "50%", top: "100px", ease: "Power2.easeInOut"});
//or you can do more advanced selecting like all the elements with the class "myClass" like this:
gsap.to(".myClass", {duration: 2, boxShadow: "0px 0px 20px red", color: "#FC0"});
By default, tweens begin immediately, although you can delay
them using the delay special property or pause
them initially using the paused special property (see below).
The target
can also be an array of objects. For example, the following tween will tween the opacity
CSS property to 0.5 and the rotation transform property to 45 for obj1, obj2, and obj3:
gsap.to([obj1, obj2, obj3], {duration: 1, opacity:0.5, rotation:45});
You can also use a Tween.from()
tween if you want to define the starting values instead of the ending values so that the target tweens from the defined values to wherever they currently are. Or a gsap.fromTo()
lets you define both starting and ending values.
If you need a reference to the GSAP instance, you can just set it equal to a variable:
var tween = gsap.to(myObject, {duration: 2, width: 200, height: 150});
Special properties, callbacks, and eases
In addition to handling the destination values of a tween, the vars object allows you to configure your tween with a variety of options.
gsap.to(element, {duration: 1, opacity: 0, onComplete: completeHandler, ease: "Back.easeOut"});
All of GSAP’s vars
properties are described below.
CHANGE FORMAT methods
-
autoCSS : Boolean - Animating CSS-related properties of DOM elements requires the CSSPlugin which means that normally you’d need to wrap CSS-related properties in a
css: {}
object likegsap.to(element, {duration: 2, css: {left: "200px", top: "100px"}, ease: "linear"});
to indicate your intent (and to tell GSAP to feed those values to the CSSPlugin), but since animating CSS-related properties is so common, GSAP implements some logic internally that allows you to omit thecss: {}
wrapper (meaning you could rewrite the above tween asgsap.to(element, {duration: 2, left: "200px", top: "100px", ease: "linear"});
). By default, it will check to see if the target is a DOM element. If so, and if you haven’t defined acss: {}
object, it will create one for you and populate it with any properties that aren’t reserved (likeonComplete
,ease
, etc. or other plugin properties) and that don’t already exist directly on the target itself (like if you created a customxpos
property on your element, that won’t get added to thecss: {}
object). To prevent GSAP from automatically creating thecss
wrapper for you, simply setautoCSS: false
. This is rarely useful, but if you suspect that GSAP is interpreting certain properties as CSS-related when it shouldn’t be, try settingautoCSS: false
or manually define your owncss: {}
object. It is perfectly acceptable to always createcss: {}
wrappers for your CSS-related properties. In fact, that results in a slight speed boost because it avoids some parsing logic when the tween gets rendered for the first time (the speed boost is probably imperceptible unless you’re tweening thousands of DOM elements simultaneously). -
callbackScope : Object - The scope to be used for all of the callbacks (
onStart
,onUpdate
,onComplete
, etc.). The scope is whatthis
refers to inside any of the callbacks. -
delay : Number - Amount of delay in seconds before the animation should begin.
-
ease : [Ease | Function | String] - You can choose from various eases to control the rate of change during the animation, giving it a specific “feel”. For example,
"Elastic.easeOut"
or"Strong.easeInOut"
. For best performance, use one of the GreenSock eases (Linear, Power0, Power1, Power2, Power3, Power4, Quad, Cubic, Quart, Quint, and Strong, each with their.easeIn
,.easeOut
, and.easeInOut
variants are included, and you can load EasePack to get extras like Elastic, Back, Bounce, SlowMo, SteppedEase, Rough, Circ, Expo, and Sine). For linear animation, use"linear"
. You can also define an ease by the ease object likeStrong.easeOut
or reverse style (like jQuery uses)"easeOutStrong"
. The default is"Quad.easeOut"
. -
immediateRender : Boolean - Normally when you create a tween, it begins rendering on the very next frame (update cycle) unless you specify a delay. However, if you prefer to force the tween to render immediately when it is created, set
immediateRender
totrue
. Or to prevent afrom()
from rendering immediately, setimmediateRender
tofalse
. By default,from()
tweens setimmediateRender
totrue
. -
lazy : Boolean - When a tween renders for the very first time and reads its starting values, GSAP will automatically “lazy render” that particular tick by default, meaning it will try to delay the rendering (writing of values) until the very end of the “tick” cycle which can improve performance because it avoids the read/write/read/write layout thrashing that some browsers do. If you would like to disable lazy rendering for a particular tween, you can set
lazy: false
. Or, since zero-duration tweens do not lazy-render by default, you can specifically give it permission to lazy-render by settinglazy: true
likegsap.set(element, {opacity: 0, lazy: true});
. In most cases, you won’t need to set lazy. To learn more, watch the video here. -
onComplete : Function - A function that should be called when the animation has completed.
-
onCompleteParams : Array - An Array of parameters to pass the
onComplete
function. For example,gsap.to(element, {duration: 1, left: "100px", onComplete: myFunction, onCompleteParams: [element, "param2"]});
. -
onStart : Function - A function that should be called when the animation begins (when its time changes from 0 to some other value which can happen more than once if the tween is restarted multiple times).
-
onStartParams : Array - An Array of parameters to pass the
onStart
function. For example,gsap.to(element, {duration: 1, x: 100, onStart: myFunction, onStartParams: [element, "param2"]});
. -
onOverwrite : Function - A function that should be called when the tween gets overwritten by another tween. The following parameters will be passed to that function:
-
overwrittenTween : Animation - The tween that was just overwritten.
-
overwritingTween : Animation - The tween did the overwriting.
-
target : Object [only passed if the overwrite mode was
"auto"
because that’s the only case when portions of a tween can be overwritten rather than the entire thing] - The target object whose properties were overwritten. This is usually the same asoverwrittenTween.target
unless that’s an array and the overwriting targeted a sub-element of that array. For example,gsap.to([obj1, obj2], {duration: 1, x: 100})
and thengsap.to(obj2, {duration: 1, x: 50})
, the target would beobj2
. -
overwrittenProperties : Array [only passed if the overwrite mode was
"auto"
because that’s the only case when portions of a tween can be overwritten rather than the entire thing] - An array of property names that were overwritten, like["x","y","opacity"]
.
-
Note: there is also a static gsap.onOverwrite
that you can use if you want a quick and easy way to be notified when any tween is overwritten (great for debugging). This saves you the hassle of defining an onOverwrite
on a tween-by-tween basis.
-
onRepeat : Function - A function that should be called each time the animation repeats.
-
onRepeatParams : Array - An Array of parameters to pass the
onRepeat
function. For example,gsap.to(element, {duration: 1, x: 100, onRepeat: myFunction, onRepeatParams: [element, "param2"]});
-
onReverseComplete : Function - A function that should be called when the animation has reached its beginning again from the reverse direction. For example, if
reverse()
is called the tween will move back towards its beginning and when itstime
reaches 0,onReverseComplete
will be called. This can also happen if the animation is placed in a timeline instance that gets reversed and plays the animation backwards to (or past) the beginning. -
onReverseCompleteParams : Array - An Array of parameters to pass the
onReverseComplete
function. For example,gsap.to(element, {duration: 1, x: 100, onReverseComplete: myFunction, onReverseCompleteParams: [element, "param2"]});
. -
onUpdate : Function - A function that should be called every time the animation updates (on every frame while the animation is active).
-
onUpdateParams : Array - An Array of parameters to pass the
onUpdate
function. For example,gsap.to(element, {duration: 1, x: 100, onUpdate: myFunction, onUpdateParams: [element, "param2"]});
. -
overwrite : [Boolearn | String] - Controls how (and if) other tweens of the same target are overwritten. The default is
false
(although you can change the default mode usinggsap.defaults({overwrite:"auto"});
. All the values you can use are as follows:-
false
(0) (or"none"
) - No overwriting will occur. -
true
(1) (or"all"
) - Immediately overwrites all tweens of the same target(s) regardless of whether or not there are duplicate/conflicting properties. -
"auto"
(2) - When the tween renders for the first time, it will analyze tweens of the same target that are currently active/running and only overwrite individual tweening properties that overlap/conflict. Tweens that haven’t begun yet are ignored. For example, if another active tween is found that is tweening 3 properties, only 1 of which it shares in common with the new tween, the other 2 properties will be left alone. Only the conflicting property gets overwritten/killed. This is the default mode and typically the most intuitive for developers.
-
-
paused : Boolean - If
true
, the animation will pause itself immediately upon creation. -
repeat : Number - Number of times that the animation should repeat after its first iteration. For example, if
repeat
is 1, the animation will play a total of twice (the initial play plus 1 repeat). To repeat indefinitely, use-1
.repeat
should always be an integer. -
repeatRefresh : Boolean - Setting
repeatRefresh: true
will cause a repeating tween toinvalidate()
and re-record its starting/ending values internally on each repeat iteration. NOTE:duration
anddelay
do NOT get refreshed on each repeat because that could lead to logical inconsistencies. UsingrepeatRefresh
only really makes sense to do when you have dynamic values (relative, random, or function-based). For example,gsap.to(".class", { duration: 1, repeat: 5, repeatRefresh: true, x: "random(-100,100)", y: "+=50" });
. -
repeatDelay : Number - Amount of time in seconds between repeats. For example, if
repeat
is 2 andrepeatDelay
is 1, the animation will play initially, then wait for 1 second before it repeats, then play again, then wait 1 second again before doing its final repeat. -
startAt : Object - Allows you to define the starting values for tweening properties. Typically, GSAP uses the current value (whatever it happens to be at the time the tween begins) as the starting value, but startAt allows you to override that behavior. Simply pass an object in with whatever properties you’d like to set just before the tween begins. For example, if
element.x
is currently100
, and you’d like to tween it from 0 to 500, dogsap.to(element, {duration: 2, x: 500, startAt: {x: 0}});
. -
yoyo : Boolean - If
true
, every other repeat cycle will run in the opposite direction so that the tween appears to go back and forth (forward then backward). This has no affect on thereversed
property though. So ifrepeat
is2
andyoyo
isfalse
, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But ifyoyo
istrue
, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end. -
yoyoEase : [Ease | Boolean] - You can set
yoyoEase
to a specific ease like"Power2.easeOut"
or to simply flip the existing ease, use the shortcutyoyoEase: true
. GSAP is smart enough to automatically setyoyo: true
if you define anyyoyoEase
, so there’s less code for you to write. Video and demos.
Plugins
Think of plugins like special properties that are dynamically added, delivering extra abilities without forcing them to be baked into the core engine, keeping it relatively lean and mean. Each plugin is associated with a property name and it takes responsibility for handling that property.
For example, the ModifiersPlugin is associated with the “modifiers” property name so if it is activated it will intercept the “modifiers” properties in the following tween and manage it in a special way:
var tween = gsap.to(".arrow", {
duration: 4,
rotation: 360,
modifiers: {
rotation: function(rotation) {
//snap to 45 degree increments
return Math.round(rotation / degrees) * degrees;
}
},
ease: "linear",
repeat: 6,
})
Function-based values
Instead of a number (x: 100
) or string (width: "300px"
) or relative value (y: "+=50"
), you can define most values as a function that’ll get called once for each target the first time the tween renders, and whatever is returned by that function will be used as the value. This can be very useful for randomizing things or applying conditional logic. See it in action in the demos below:
Parameters: index, target
The function is passed two parameters:
-
index (integer) - the target’s position in the array of targets. For example, if there are 3
<div>
elements with the class “.box”, and yougsap.to(".box", ...)
, the function would get called 3 times (once for each target) and the index would be0
first, then1
, and finally2
. -
target (object) - the target itself (the
<div>
element in this case)
Using the index parameter makes it easy to increment the value accordingly. There are lots of ways to get creative. The demo below uses the index parameter to tween each element’s x value in increments of 100.
Examples
Please see the GSAP page for examples, tutorials, and interactive demos.
Notes / Tips
-
Passing values as Strings and preceding
"+="
or"-="
will make the tween relative to the current value. For example, if you dogsap.to(element, {duration: 2, left: "-=20px"});
it’ll tween left to 20 pixels less than whatever it is when the tween starts.{x: "+=20"}
would add 20. -
If you change
gsap.to
calls (likegsap.to(...).to(...)
) GSAP will automatically create and return agsap.timeline
instance for you. However, you cannot setdefaults
, event listeners, or anything else on that timeline using this method. In order to do that, use thegsap.timeline()
method. -
You can change the default ease by setting
gsap.default({ease: ...});
. The default is"Power1.easeOut"
. -
You can kill all tweens of a particular object anytime with
gsap.killTweensOf(yourObject);
You can also use selector text likegsap.killTweensOf("#someID");
-
You can kill all
delayedCall
s to a particular function withgsap.killDelayedCallsTo(myFunction)
orgsap.killTweensOf(myFunction);
-
If you find this class useful, please consider joining Club GreenSock which not only helps to sustain ongoing development, but also gets you bonus plugins, classes and other benefits that are ONLY available to members. Learn more at the club page.