Skip to main content

Tween Control: Free GreenSock Tutorial

Master GreenSock Animation Control with Professional Tweening

Core GreenSock Concepts You'll Master

Element Positioning

Learn to use Set() method for instant positioning changes without animation duration. Perfect for setting initial states.

Transform Origins

Control the exact point around which rotations and transforms occur. Rotate from corners, edges, or custom positions.

Tween Control

Master play(), reverse(), and pause() methods to create interactive animations that respond to user input dynamically.

Topics Covered in This GreenSock Tutorial:

Using Set() to Change an Element's Position, the TransformOrigin Property, Controlling the Direction of Rotation, Giving a Tween a Var Reference, the Play() & Reverse() Methods

Exercise Preview

exercise preview tween control

Exercise Overview

In this exercise, we'll dive deep into the sophisticated animation control capabilities that make GreenSock (GSAP) the animation library of choice for professional web developers. TweenLite tweens offer granular control through methods like play(), pause(), reverse(), and resume()—giving you the power to create highly interactive, user-responsive animations that adapt to real-time user input.

We'll also explore the transformOrigin property, a powerful feature that provides precise control over the pivot point of transformations. Whether you need to rotate an element around its bottom-left corner, scale from the top-right, or create complex mechanical animations like our speedometer example, understanding transformOrigin is essential for professional-grade animation work. This level of control was previously difficult to achieve with CSS alone and often required complex mathematical calculations.

Animation Development Workflow

1

Preview Target Animation

Open finished.html in Chrome to understand the final interactive speed gauge animation behavior

2

Analyze DOM Structure

Examine the HTML structure with speedGauge div containing pointer and center images

3

Position Elements

Use Set() method to move pointer to correct starting position before animation begins

4

Configure Transforms

Set transformOrigin property to control rotation point and direction specifiers for clockwise motion

5

Add Interactivity

Implement mouseenter and mouseleave events to control tween playback and reversal

Previewing the Finished Animation

  1. To examine the animation we'll be building, launch Google Chrome (or your preferred modern browser).

  2. Hit Cmd–O (Mac) or CTRL–O (Windows), navigate to Desktop > Class Files > yourname-GSAP Class > Tween Control, and double–click on finished.html.

  3. Hover your mouse over the speed gauge to trigger the animation. The pointer smoothly "accelerates" in a clockwise direction, as demonstrated in the exercise preview above.

  4. Move your mouse away at any point to reverse the animation. Notice how the animation doesn't need to complete its full cycle before reversing—this seamless bidirectional control is one of GSAP's most powerful features. Try hovering on and off rapidly to observe how the tween intelligently transitions between play and reverse states from any point in the timeline.

  5. Interact with the speed gauge multiple times to fully appreciate the smooth, responsive nature of the animation and how it maintains consistent easing throughout both directions.

This type of interactive animation is commonly used in dashboard interfaces, data visualizations, and interactive infographics where users expect immediate visual feedback to their actions.

Examining the DOM Structure

  1. Open your code editor and load start.html from the Tween Control folder.

  2. Examine the DOM structure in lines 34–37 to understand our animation targets:

    <div id="speedGauge">
       <img id="pointer" src="img/pointer.png" height="9" width="89">
       <img id="center" src="img/disc.png" height="41" width="40">
    </div>

    The markup is deliberately simple: two images nested within a container div. The pointer element is our primary animation target, while the center image serves as the visual hub of our gauge. The speedGauge container uses a background image to complete the gauge's visual design—a common pattern that separates decorative elements from functional animation targets.

  3. Preview start.html in your browser to see the current state without any animations applied.

    You'll immediately notice that the pointer is positioned incorrectly for our speedometer interface. Currently, it sits at the default browser position, but we need it aligned with the first notch on the left side of our gauge. This positioning challenge is exactly why we need GSAP's set() method—it allows us to establish proper initial states before beginning our animations.

    pointer default position vs. desired start position

DOM Structure Foundation

The animation relies on a simple structure: a speedGauge container div with two images - the pointer we'll animate and a center disc. The gauge background is applied via CSS to the container div.

Using Set() to Change an Element's Position

  1. Return to your code editor and locate lines 50–51, where you'll find these essential variables that will drive our animation:

    $(document).ready(function() {
    
       var $gauge = $("#speedGauge"), 
           $pointer = $("#pointer");

    Note the jQuery convention of prefixing variables with $ to indicate they contain jQuery objects—this makes code more readable and helps prevent confusion between DOM elements and jQuery-wrapped elements.

  2. Before implementing our rotation animation, let's establish the strategy: we need to position the pointer correctly using transformations that would traditionally require extensive CSS and vendor prefixes. GSAP eliminates this complexity, allowing us to achieve professional results with minimal code.

  3. The set() method is GSAP's solution for instant transformations—essentially a zero-duration tween that applies immediately. After the $pointer variable declaration, press Return twice and add this code:

    $pointer = $("#pointer");
    
    TweenLite.set($pointer, {rotation:90});

    The syntax mirrors the familiar to() and from() methods, but without a duration parameter. This makes set() perfect for establishing initial states, responsive design adjustments, or any transformation that needs to happen instantly without animation.

  4. Save your file and refresh the browser. The pointer now rotates 90°, but it's rotating around its center point—creating an undesirable visual effect for our speedometer interface.

    set method first test needs transformorigin

Set() vs Traditional CSS Approach

FeatureGreenSock Set()Traditional CSS
Code LinesSingle lineMultiple lines
Vendor PrefixesAutomaticManual required
Animation DurationInstant (0)Must specify
Cross-browserBuilt-in supportManual testing
Recommended: GreenSock Set() eliminates the complexity of vendor prefixes and cross-browser compatibility issues.

The TransformOrigin Property

By default, CSS transformations originate from an element's center point—a behavior that works well for simple scaling effects but fails for mechanical animations like gauges, clock hands, or rotating dials. The transformOrigin property gives you pixel-perfect control over the rotation pivot point, enabling realistic mechanical animations and complex interface behaviors.

  1. Return to your code editor and enhance the set() method with a precise transform origin:

    TweenLite.set($pointer, {rotation:90, transformOrigin:"0px 4px"});

    The string values represent horizontal and vertical positions respectively. Our values specify that the pointer should rotate around a point 0 pixels from the left edge and 4 pixels down from the top—positioning the pivot at the base of the pointer where it would naturally connect to a speedometer mechanism.

    pointer transform origin example

  2. Save and preview the page. While the 90° rotation places our pointer at the bottom (6 o'clock position) rather than our desired starting point, you can see that the rotation pivot is now perfectly positioned. This precise control over the transform origin is what enables professional-looking mechanical animations.

    gauge with pointer at six oclock

  3. Return to your code editor to fine-tune the rotation value.

  4. TransformOrigin accepts various CSS units, with pixels offering the most precision for mechanical animations and percentages providing responsive scaling. Consider these options for your future projects:

Transform Origin Values

The string value describes the horizontal and vertical positions. You can define transform-origin values using multiple approaches:

  • Keywords: Use intuitive terms like "left center" or "right bottom" for quick positioning
  • Percentages: "100% 100%" positions the origin at the bottom-right corner, perfect for responsive designs
  • Pixel values: "100px 50px" provides exact positioning, ideal for precise mechanical animations
  • Mixed units: "50% bottom" combines responsive and absolute positioning for complex layouts

For professional animation work, pixel values often provide the most predictable results, while percentages excel in responsive design contexts.

  • Ensure your code matches this exact syntax before proceeding:

    TweenLite.set($pointer, {rotation:90, transformOrigin:"0px 4px"});
  • Now let's position the pointer at its correct starting position. Change the rotation value to 142 degrees:

    TweenLite.set($pointer, {rotation:142, transformOrigin:"0px 4px"});

    This specific angle aligns the pointer with the leftmost notch of our speedometer, creating the proper "idle" state before animation begins.

  • Save and preview the page. Perfect! The pointer now assumes its correct starting position at the bottom-left of the gauge, ready for our interactive animation sequence.

  • Transform Origin Options

    Keywords

    Use descriptive terms like 'left', 'right', 'center', 'top', 'bottom' for intuitive positioning. Example: 'right bottom'.

    Percentages

    Relative positioning where '100% 100%' equals bottom-right corner. Scales with element size changes automatically.

    Pixel Values

    Exact positioning for precise control. '100px' means 100 pixels from both top and left edges of the element.

    Mixed Approaches

    Combine different units like '50% bottom' for horizontal percentage positioning with vertical keyword alignment.

    Controlling the Direction of Rotation

    With our pointer properly positioned, we can now create the animation that will respond to user interaction. However, rotation direction requires careful consideration—GSAP's intelligent path-finding might not always match your design intentions.

    1. In your code editor, add this TweenLite.to() method after the set() method:

      TweenLite.set($pointer, {rotation:142, transformOrigin:"0px 4px"});
      
      TweenLite.to($pointer, 1, {rotation:20, ease:Power1.easeIn});
    2. Note these important implementation details:

      • Transform origin inheritance: We don't need to redefine transformOrigin—GSAP intelligently maintains the previous value throughout the animation timeline
      • Built-in easing: Power1.easeIn comes packaged with TweenLite, providing smooth acceleration without requiring additional plugins—perfect for mechanical animations that need to feel natural
    3. Save and preview the page. The pointer reaches the correct end position, but it rotates counterclockwise—the opposite of what we want for a speedometer acceleration effect.

    4. GSAP provides explicit directional control to override its automatic shortest-path behavior. Return to your code editor and modify the rotation property:

    5. Add the clockwise specifier to force the desired rotation direction:

      TweenLite.to($pointer, 1, {rotation:"20_cw", ease:Power1.easeIn});

      The _cw suffix overrides GSAP's default shortest-path rotation, ensuring our speedometer behaves like a real mechanical gauge. This level of control is essential for creating believable interface animations.

    Rotation Specifiers

    GSAP provides three directional controls for rotation animations:

    _cw Forces clockwise rotation regardless of shortest path
    _ccw Forces counterclockwise rotation for reverse effects
    _short Explicitly uses shortest path (GSAP's default behavior)

    These specifiers are particularly valuable in dashboard interfaces, loading spinners, and mechanical simulations where rotation direction affects user perception and interface logic.

  • Save and preview the page. Excellent! The animation now moves in the correct clockwise direction, creating the expected speedometer acceleration effect.

  • Understanding rotation values is crucial for complex animations. Even though we used set() to establish a 142° starting position, GSAP treats the target rotation of 20° as relative to the element's original 0° state, not the modified position. This behavior allows for consistent animation logic regardless of initial transformations.

    pointer states example

  • Rotation Direction Control

    _cw (Clockwise)
    100
    _ccw (Counter-clockwise)
    85
    _short (Shortest path)
    70

    Giving a Tween a Var Reference

    1. To create interactive animations that respond to user input, we need programmatic access to our tween instance. Assign the tween to a variable for later control:

      var pointerTween = TweenLite.to($pointer, 1, {rotation:"20_cw", ease:Power1.easeIn});

      This variable reference transforms our basic animation into a controllable animation instance—the foundation for sophisticated interactive experiences in modern web applications.

    2. Currently, our animation plays immediately when the page loads. For user-controlled interactions, we need to pause it by default. Add the pause() method below your tween:

      var pointerTween = TweenLite.to($pointer, 1, {rotation:"20_cw", ease:Power1.easeIn});
      
      pointerTween.pause();
    3. Save and preview the page. The animation is now paused, waiting for user interaction to trigger playback.

    4. Remove the pause() method line you just added—we'll use a more efficient approach.

    5. GSAP allows you to set the paused state directly in the tween constructor, creating cleaner, more maintainable code. Add the paused property to your tween configuration:

      var pointerTween = TweenLite.to($pointer, 1, {rotation:"20_cw", ease:Power1.easeIn, paused:true});

      This approach keeps all tween configuration in one location and is the preferred method for professional GSAP development.

    Variable References Enable Control

    Assigning tweens to variables is essential for interactive animations. Without a reference, you cannot pause, play, reverse, or otherwise control the tween after creation.

    Pausing Methods Comparison

    Pros
    Constructor paused:true property keeps code compact
    Method-based pause() offers more flexibility for conditional logic
    Both approaches achieve identical results
    Constructor approach reduces separate method calls
    Cons
    Method-based approach requires additional line of code
    Constructor approach less obvious for debugging
    Multiple pause points need method-based approach

    The Play() & Reverse() Methods

    1. Now we'll create the interactive behavior that makes our speedometer responsive to user input. Add this mouseenter event handler:

      var pointerTween = TweenLite.to($pointer, 1, {rotation:"20_cw", ease:Power1.easeIn, paused:true});
      
      $gauge.mouseenter( function() {
         pointerTween.play();
      });

      The mouseenter() event provides clean hover detection without the bubbling issues of mouseover, making it ideal for interface animations. When users hover over the gauge, the play() method resumes the tween from its current position—whether that's the beginning, middle, or any other point in the timeline.

    2. Save and preview the page in your browser.

    3. Hover over the gauge to see the animation spring to life. The smooth acceleration creates an engaging visual feedback that enhances the user experience.

    4. Move your mouse away from the gauge—notice that nothing happens yet. Let's add the complementary behavior.

    5. Complete the interactive experience by adding the mouseleave handler:

      $gauge.mouseenter( function() {
         pointerTween.play();
      });
      
      $gauge.mouseleave( function() {
         pointerTween.reverse();
      });

      The reverse() method is where GSAP's sophistication truly shines—it doesn't simply reset the animation, but intelligently reverses from the current position while maintaining the original easing curve and timing. This creates seamless bidirectional animations that feel natural and responsive.

    6. Save and test the complete interaction:

      • Hover over the speed gauge to trigger the forward animation
      • Move your mouse away to see the smooth reverse animation with preserved easing and timing
      • Try rapid on-off movements to appreciate how GSAP handles mid-timeline reversals without jarring transitions

      This level of smooth, reversible animation control is what separates professional-grade web animations from basic CSS transitions and is essential for creating engaging user interfaces in modern web applications.

    Interactive Animation Implementation

    1

    Create Paused Tween

    Initialize tween with paused:true property to prevent automatic playback on page load

    2

    Add Mouse Enter Handler

    Use jQuery mouseenter() event to trigger pointerTween.play() when user hovers over gauge

    3

    Add Mouse Leave Handler

    Implement mouseleave() event with pointerTween.reverse() to smoothly reverse animation from current position

    Seamless Reversal Capability

    GreenSock's reverse() method maintains timing and easing properties when reversing from any point in the animation, creating fluid user interactions without jarring transitions.

    Key Takeaways

    1GreenSock's Set() method provides instant element positioning without animation duration, eliminating the need for complex CSS vendor prefixes
    2Transform origin property controls the rotation point of elements, enabling precise control over where transforms originate using keywords, percentages, or pixel values
    3Rotation direction specifiers (_cw, _ccw, _short) give developers explicit control over animation direction rather than relying on shortest-path defaults
    4Assigning tweens to variables enables programmatic control through methods like play(), pause(), and reverse() for interactive animations
    5Constructor-based properties like paused:true offer cleaner code organization compared to separate method calls for tween control
    6jQuery event handlers like mouseenter() and mouseleave() integrate seamlessly with GreenSock tween controls for responsive user interactions
    7GreenSock's reverse() method preserves timing and easing properties when reversing from any animation point, maintaining smooth motion
    8Power eases come packaged with TweenLite, reducing dependency requirements while providing professional animation curves for enhanced user experience

    RELATED ARTICLES