Jump to content
GreenSock

TweenLite

TweenLite is an extremely fast, lightweight, and flexible animation tool that serves as the foundation of the GreenSock Animation Platform (GSAP). A TweenLite instance handles tweening one or more properties of any object (or array of objects) over time. TweenLite can be used on its own to accomplish most animation chores with minimal file size or it can be used in conjunction with advanced sequencing tools like TimelineLite or TimelineMax to make complex tasks much simpler. With scores of other animation frameworks to choose from, why consider the GSAP?:

  • SPEED - The platform has been highly optimized for maximum performance. See some speed comparisons yourself at http://greensock.com/js/speed.html
  • Freakishly robust feature set - In addition to tweening any numeric property of any object, TweenLite has plugins that give it the ability to tween hex colors, beziers, CSS, SVG, do morphing, 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()/resume() anytime, and intelligently manage conflicting tweens of the same object with various overwrite modes. TweenMax extends TweenLite and adds even more capabilities like repeat, yoyo, repeatDelay, and more.
  • Sequencing, grouping, and management features - TimelineLite and TimelineMax 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

To get up and running quickly, check out the Getting Started guide.

The most common type of tween is a TweenLite.to() tween which allows you to define the destination values:

var photo = document.getElementById("photo");
TweenLite.to(photo, 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. To animate css properties, you'll need to use the CSSPlugin. The CSSPlugin contains special code for deciphering css-related properties and handling them in unique ways, like recognizing colors, transforms, etc. and managing the necessary suffixes ("px", "%", etc.).

If you pass a string (text) into a tween as the target (like TweenLite.to("#myID", 1, {left:"100px"})) TweenLite 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 TweenLite and CSSPlugin are loaded, you can easily animate things like this:

//tween the element with ID of "myID"
TweenLite.to("#myID", 2, {backgroundColor:"#ff0000", width:"50%", top:"100px", ease:Power2.easeInOut});
 
//tween every element with the class "myClass" like this: 
TweenLite.to(".myClass", 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:

TweenLite.to([obj1, obj2, obj3], 1, {opacity:0.5, rotation:45});

Normally, css-specific properties would need to be wrapped in their own object and passed in like TweenLite.to(element, 1, {css:{left:"100px", top:"50px"}}); so that the engine knows that those properties belong to the CSSPlugin, but because animating DOM elements in the browser with CSSPlugin is so common, TweenLite automatically checks to see if the target is a DOM element and if it is (and you haven't defined a "css" object in the vars), TweenLite creates that css object for you and shifts any properties that aren't already defined directly on the element or reserved (like onComplete, ease, delay, etc. or plugins) into that css object when the tween renders for the first time.

You can also use a TweenLite.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 TweenLite.fromTo() lets you define both starting and ending values.

Although the to(), from(), and fromTo() static methods are popular because they're quick and can avoid some garbage collection hassles, you can also use the more object-oriented syntax like this:

var tween = new TweenLite(element, 2, {width:200, height:150});

or even:

var tween = TweenLite.to(element, 2, {width:200, height:150});

Special properties, eases and callbacks (no plugins required):

Typically the vars parameter is used to define ending values for tweening properties of the target (or beginning values for from() tweens) like {left:"100px", top:"200px", opacity:0}, but the following optional special properties serve other purposes:

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 CSSPlugin is associated with the "css" property name so if it is activated it will intercept the "css" property in the following tween and manage it in a special way so that the tweens affect the element's style object (for manipulating DOM elements):

TweenLite.to(element, 1, {css:{top:"100px", left:"50px", backgroundColor:"#ff0000", fontSize:"12px"}, delay:0.5});

But again, CSSPlugin is a special case where TweenLite (as of version 1.8.0) doesn't require wrapping css-specific properties in a css object (although you can if you want maximum performance).

If the CSSPlugin wasn't loaded, TweenLite would act as though you were trying to literally tween the element.css property (and there is no such thing).

Function-based values

Instead of a number (x:100) or string (width:"300px") or relative value (y:"+=50"), you can now 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 TweenLite.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 http://greensock.com/gsap-js/ for more examples, tutorials, and interactive demos.

Official GreenSock Training (videos and eBook)

If you want to learn all of what GSAP can do check out our official video training Learn HTML5 Animation with GreenSock which includes over 5 hours of HD video created by our Geek Ambassador, Carl Schooff. This course is packed with real-world projects and detailed step-by-step instructions.

Notes / tips:

  • Passing values as Strings and a preceding "+=" or "-=" will make the tween relative to the current value. For example, if you do TweenLite.to(element, 2, {left:"-=20px"}); it'll tween left to 20 pixels less than whatever it is when the tween starts. {x:"+=20"} would add 20.
  • You can change the TweenLite.defaultEase if you prefer something other than Power1.easeOut.
  • Kill all tweens of a particular object anytime with TweenLite.killTweensOf(yourObject);. You can also use selector text like TweenLite.killTweensOf("#myID");
  • You can kill all delayedCalls to a particular function using TweenLite.killDelayedCallsTo(myFunction); or TweenLite.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 http://greensock.com/club/

Constructor

TweenLite( target:Object, duration:Number, vars:Object ) ;

TweenLite Constructor creates a tween.

Properties

data : *

A place to store any data you want (initially populated with vars.data if it exists).

defaultEase : Ease

[static] Provides An easy way to change the default easing equation.

defaultOverwrite : String = "auto"

[static] Provides An easy way to change the default overwrite mode.

onOverwrite : Function

[static] A function that should be called when any tween gets overwritten by another tween (great for debugging).

selector : * = document.getElementById()

[static] The selector engine (like jQuery, but defaults to document.querySelectorAll()) to use when a tween receives a string as its target, like "#myID".

target : Object

[READ-ONLY] Target object (or array of objects) whose properties the tween affects.

ticker : Object

[static] The object that dispatches a "tick" event each time the engine updates, making it easy for you to add your own listener(s) to run custom logic after each update (great for game developers).

timeline : SimpleTimeline

[Read-only] Parent timeline.

vars : Object

The vars object passed into the constructor which stores configuration variables like onComplete, onUpdate, etc.

Methods

delay( value:Number ) : *

Gets or sets the animation's initial delay which is the length of time in seconds (or frames for frames-based tweens) before the animation should begin.

delayedCall( delay:Number, callback:Function, params:Array , scope:*, useFrames:Boolean ) : TweenLite

[static] Provides a simple way to call a function after a set amount of time (or frames).

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, duration:Number, vars:Object ) : TweenLite

[static] Static method for creating a TweenLite 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, duration:Number, fromVars:Object, toVars:Object ) : TweenLite

[static] Static method for creating a TweenLite 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).

getTweensOf( target:*, onlyActive:Boolean ) : Array

[static] Returns an array containing all the tweens of a particular target (or group of targets) that have not been released for garbage collection yet which typically happens within a few seconds after the tween completes.

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

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

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

killDelayedCallsTo( func:Function ) :

[static] Immediately kills all of the delayedCalls to a particular function.

killTweensOf( target:Object, onlyActive:Boolean, vars:Object ) :

[static] Kills all the tweens (or specific tweening properties) of a particular object or delayedCalls to a particular function.

lagSmoothing( threshold:Number, adjustedLag:Number ) :

Permits you to control what happens when too much time elapses between two ticks (updates) of the engine, adjusting the core timing mechanism to compensate and avoid "jumps".

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 ) : *

Gets or sets the animations'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 at the halfway point, and 1 is at the end (complete).

render( ) :

Forces a render of all active tweens which can be useful if, for example, you set up a bunch of from() tweens and then you need to force an immediate render (even of "lazy" tweens) to avoid a brief delay before things render on the very next tick.

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 ) : TweenLite

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

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

Gets or sets the local position of the playhead (essentially the current time), described in seconds (or frames for frames-based animations) which will never be less than 0 or greater than the animation's duration.

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, duration:Number, vars:Object ) : TweenLite

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

totalDuration( value:Number ) : *

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

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

Gets or sets the animation's total progress 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 at the halfway point, and 1 is at the end (complete).

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

Gets or sets the position of the playhead according to the totalDuration which includes any repeats and repeatDelays (only available in TweenMax and TimelineMax).

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