Jump to content
GreenSock

Tween

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 Timelines 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() and resume() 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(), or reverse(). You can even tween a timeline's time() or progress() to fastforward or rewind the entire timeline. Add labels, change the timeline's timeScale, 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:

  1. var photo = document.getElementById("photo");
  2. 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:

  1. //tween the element with ID of "myID"
  2. gsap.to("#myID", {duration: 2, backgroundColor: "#ff0000", width: "50%", top: "100px", ease: "Power2.easeInOut"});
  3. //or you can do more advanced selecting like all the elements with the class "myClass" like this:
  4. 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:

  1. 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:

  1. 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.

  1. 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 like gsap.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 the css: {} wrapper (meaning you could rewrite the above tween as gsap.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 a css: {} object, it will create one for you and populate it with any properties that aren’t reserved (like onComplete, ease, etc. or other plugin properties) and that don’t already exist directly on the target itself (like if you created a custom xpos property on your element, that won’t get added to the css: {} object). To prevent GSAP from automatically creating the css wrapper for you, simply set autoCSS: false. This is rarely useful, but if you suspect that GSAP is interpreting certain properties as CSS-related when it shouldn’t be, try setting autoCSS: false or manually define your own css: {} object. It is perfectly acceptable to always create css: {} 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 what this 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 like Strong.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 to true. Or to prevent a from() from rendering immediately, set immediateRender to false. By default, from() tweens set immediateRender to true.

  • 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 setting lazy: true like gsap.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:

    1. overwrittenTween : Animation - The tween that was just overwritten.

    2. overwritingTween : Animation - The tween did the overwriting.

    3. 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 as overwrittenTween.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 then gsap.to(obj2, {duration: 1, x: 50}), the target would be obj2.

    4. 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 its time 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 using gsap.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 to invalidate() and re-record its starting/ending values internally on each repeat iteration. NOTE: duration and delay do NOT get refreshed on each repeat because that could lead to logical inconsistencies. Using repeatRefresh 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 and repeatDelay 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 currently 100, and you’d like to tween it from 0 to 500, do gsap.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 the reversed property though. So if repeat is 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But if yoyo is true, 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 shortcut yoyoEase: true. GSAP is smart enough to automatically set yoyo: true if you define any yoyoEase, 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:

  1. var tween = gsap.to(".arrow", {
  2. duration: 4,
  3. rotation: 360,
  4. modifiers: {
  5. rotation: function(rotation) {
  6. //snap to 45 degree increments
  7. return Math.round(rotation / degrees) * degrees;
  8. }
  9. },
  10. ease: "linear",
  11. repeat: 6,
  12. })

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:

  1. index (integer) - the target’s position in the array of targets. For example, if there are 3 <div> elements with the class “.box”, and you gsap.to(".box", ...), the function would get called 3 times (once for each target) and the index would be 0 first, then 1, and finally 2.

  2. 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 do gsap.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 (like gsap.to(...).to(...)) GSAP will automatically create and return a gsap.timeline instance for you. However, you cannot set defaults, event listeners, or anything else on that timeline using this method. In order to do that, use the gsap.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 like gsap.killTweensOf("#someID");

  • You can kill all delayedCalls to a particular function with gsap.killDelayedCallsTo(myFunction) or gsap.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.

Properties

data : *

vars : Object

Methods

delay( value:Number ) : *

Gets or sets the animation's initial delay which is the length of time in seconds before the animation should begin.

duration( value:Number ) : *

Gets or sets the animation's duration, not including any repeats or repeatDelays (which are only available in TweenMax and TimelineMax).

endTime( includeRepeats:Boolean ) : Number

Returns the time at which the animation will finish according to the parent timeline's local time.

eventCallback( type:String, callback:Function, params:Array, scope:* ) : *

Gets or sets an event callback like "onComplete", "onUpdate", "onStart", "onReverseComplete" or "onRepeat" (onRepeat only applies to TweenMax or TimelineMax instances) along with any parameters that should be passed to that callback.

from( target:Object, vars:Object ) : Tween

[static] Static method for creating a Tween instance that tweens backwards - you define the BEGINNING values and the current values are used as the destination values which is great for doing things like animating objects onto the screen because you can set them up initially the way you want them to look at the end of the tween and then animate in from elsewhere.

fromTo( target:Object, fromVars:Object, toVars:Object ) : Tween

[static] Static method for creating a Tween instance that allows you to define both the starting and ending values (as opposed to to() and from() tweens which are based on the target's current values at one end or the other).

invalidate( ) : *

[override] Flushes any internally-recorded starting/ending values which can be useful if you want to restart an animation without reverting to any previously recorded starting values.

isActive( ) : Boolean

Indicates whether or not the animation is currently active (meaning the virtual playhead is actively moving across this instance's time span and it is not paused, nor are any of its ancestor timelines).

iteration( ) : *

Gets or sets the iteration (the current repeat) of tweens.

kill( vars:Object, target:Object ) : *

Kills the animation entirely or in part depending on the parameters.

pause( atTime:*, suppressEvents:Boolean ) : *

Pauses the instance, optionally jumping to a specific time.

paused( value:Boolean ) : *

Gets or sets the animation's paused state which indicates whether or not the animation is currently paused.

play( from:*, suppressEvents:Boolean ) : *

Begins playing forward, optionally from a specific time (by default playback begins from wherever the playhead currently is).

progress( value:Number, suppressEvents:Boolean ) : *

[override] Gets or sets the tween's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is halfway complete, and 1 is complete.

repeat( value:Number ) : *

Gets or sets the number of times that the tween should repeat after its first iteration.

repeatDelay( value:Number ) : *

Gets or sets the amount of time in seconds between repeats.

restart( includeDelay:Boolean, suppressEvents:Boolean ) : *

Restarts and begins playing forward from the beginning.

resume( from:*, suppressEvents:Boolean ) : *

Resumes playing without altering direction (forward or reversed), optionally jumping to a specific time first.

reverse( from:*, suppressEvents:Boolean ) : *

Reverses playback so that all aspects of the animation are oriented backwards including, for example, a tween's ease.

reversed( value:Boolean ) : *

Gets or sets the animation's reversed state which indicates whether or not the animation should be played backwards.

seek( time:*, suppressEvents:Boolean ) : *

Jumps to a specific time without affecting whether or not the instance is paused or reversed.

set( target:Object, vars:Object ) : Tween

[static] Immediately sets properties of the target accordingly - essentially a zero-duration to() tween with a more intuitive name.

startTime( value:Number ) : *

Gets or sets the time at which the animation begins on its parent timeline (after any delay that was defined).

then( callback:Function ) : Promise

Returns a promise so that you can uses promises to track when a tween or timeline is complete.

time( value:Number, suppressEvents:Boolean ) : *

[override] Gets or sets the local position of the playhead (essentially the current time), not including any repeats or repeatDelays.

timeScale( value:Number ) : *

Factor that's used to scale time in the animation where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc.

to( target:Object, vars:Object ) : *

[static] Static method for creating a Tween instance that animates to the specified destination values (from the current values).

totalDuration( value:Number ) : *

[override] Gets or sets the total duration of the tween in seconds including any repeats or repeatDelays.

totalProgress( value:Number, suppressEvents:Boolean ) : *

[override] Gets or sets the tween's totalProgress which is a value between 0 and 1 indicating the position of the virtual playhead (including repeats) where 0 is at the beginning, 0.5 is halfway complete, and 1 is complete.

totalTime( time:Number, suppressEvents:Boolean ) : *

Gets or sets the position of the playhead according to the totalDuration which includes any repeats and repeatDelays.

yoyo( value:Boolean ) : *

Gets or sets the tween's yoyo state, where true causes the tween to go back and forth, alternating backward and forward on each repeat.

Copyright 2017, GreenSock. All rights reserved. This work is subject to theterms of useor for Club GreenSock members, the software agreement that was issued with the membership.
×