Skip to main content

Tween Methods & Callbacks

Master GreenSock Animation Controls and Event Handling

Core GreenSock Concepts You'll Learn

Getter/Setter Methods

Master duration(), time(), and timeScale() methods for dynamic tween control. Learn to both retrieve and modify tween properties programmatically.

Event Callbacks

Implement onUpdate, onStart, onComplete, and other callbacks to execute custom functions at specific animation events.

Interactive Animation

Create responsive animations that react to user interactions like mouse events with proper speed and timing controls.

Topics Covered in This GreenSock Tutorial:

Getting & Setting Tween-related Values, Event Callbacks, Changing a Tween's TimeScale()

Exercise Preview

exercise preview tween methods&callbacks

Exercise Overview

In this comprehensive exercise, we'll dive deep into TweenLite's advanced methods that provide precise control over animations while exposing critical tween data. You'll master event callbacks—powerful functions that execute at specific animation milestones, enabling sophisticated interactive behaviors that respond dynamically to user actions. These techniques form the foundation of professional-grade web animations used by leading digital agencies and interactive studios worldwide.

Building on Previous Knowledge

This exercise expands on the previous speed gauge example, adding numerical display and advanced interaction patterns. You'll implement dynamic value updates and variable playback speeds.

Previewing the Finished Animation

  1. We'll build upon the previous exercise's foundation to create an enhanced interactive speed gauge. Launch Google Chrome to examine the completed implementation.

  2. Press Cmd–O (Mac) or CTRL–O (Windows), navigate to Desktop > Class Files > yourname-GSAP Class > Tween Methods and Callbacks, and open finished.html.

    Notice the familiar gauge interface now features a prominent numerical display showing a zero value to the right of the speed indicator.

  3. Hover over the speed gauge to trigger the animation sequence. Watch as the numerical display dynamically updates, showing increasing values that correspond precisely to the gauge needle's clockwise rotation.

  4. Move your cursor away from the gauge to observe the reverse animation behavior. The tween not only reverses direction but accelerates significantly, demonstrating advanced timeScale manipulation.

  5. While hovering over the active gauge, click to activate the restart functionality. This immediately resets the pointer to its initial bottom-left position. Though the animation plays too rapidly to catch the zero value, you'll observe double-digit numbers appearing as the gauge accelerates through its sequence—a sophisticated touch that enhances user feedback.

  6. Experiment with multiple hover and click interactions to fully appreciate the animation's responsive behavior and smooth state transitions.

Animation Interaction Flow

1

Mouse Over

Speed gauge animates clockwise at normal speed while numbers increase from 0 to 750

2

Mouse Out

Animation reverses at 6x accelerated speed back to starting position

3

Click Interaction

Clicking restarts the entire animation from the beginning position instantly

Examining the DOM Structure & JavaScript

Before implementing advanced tween methods, let's analyze the underlying code architecture that makes this interactive animation possible.

  1. Open start.html from the Tween Methods and Callbacks folder in your preferred code editor.

  2. Examine lines 52–58 to understand the revised DOM structure. The layout has been refined from the previous exercise with all elements now enclosed within a centralized wrapper div. The numberDisplay div, highlighted in bold below, initializes with a zero value and serves as our dynamic speed indicator:

    <div id="wrapper">
       <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>
       <div id="numberDisplay">0</div>
    </div>
  3. Review the JavaScript variables around lines 70–74. The original $gauge and $pointer variables are now joined by three strategic additions shown in bold:

    var $gauge = $("#speedGauge"), 
        $pointer = $("#pointer"), 
        $numberDisplay = $("#numberDisplay"), 
        displayValue, 
        finalValue = 750;
  4. Understanding these new variables is crucial for the animation logic:

    • $numberDisplay provides jQuery access to the numerical display element, enabling real-time content updates during animation.
    • displayValue stores the calculated numerical value that users see in the speedometer display, updated continuously during tween execution.
    • finalValue defines the maximum numerical value (750), establishing the upper bound for our speed calculation algorithm.
  5. Preview start.html in Chrome to observe the initial state. The pointer rests at its starting position (bottom-left), while the numerical display shows the default zero value.

  6. Test the current hover functionality by moving your cursor over the gauge. The pointer animation executes correctly, but the numerical display remains static—this is the functionality we'll implement next.

  7. Move your cursor away from the gauge to observe the reverse animation. Note that it currently plays at the same speed as the forward animation—we'll enhance this with accelerated reverse playback.

All elements are now enclosed in a wrapper div that centers everything on the page. The div with an ID of numberDisplay has an initial value set to zero.
Key structural changes from the previous exercise that enable the numerical display functionality.

New JavaScript Variables

$numberDisplay

jQuery selector targeting the div where animated numbers appear in the speedometer interface.

displayValue

Holds the calculated value that gets displayed to users as the animation progresses.

finalValue

Set to 750, represents the maximum value the animation will reach at completion.

Getting & Setting Tween-Related Values

GSAP's getter/setter methods provide powerful runtime control over animation properties. These dual-purpose methods enable both data retrieval and dynamic modification, essential for creating adaptive animations that respond to user interaction or application state changes.

The duration() method exemplifies this flexibility—use it to query a tween's duration or modify it on-the-fly without recreating the entire animation object.

  1. Implement the duration() method as a getter by adding the following code below the pointerTween object (around line 81):

    var pointerTween = TweenLite.to($pointer, 1, {rotation:"20_cw", transformOrigin:"0px 4px", paused:true, ease:Power1.easeIn});
    
    console.log("tween duration = " + pointerTween.duration());
  2. Save your file and preview the page in Chrome.

  3. Access Chrome's DevTools Console by CTRL–clicking (Mac) or Right–clicking (Windows) on the page, selecting Inspect, and clicking the Console tab. Alternatively, use Cmd–Opt–J (Mac) or CTRL–Shift–J (Windows).

    The Console displays: tween duration = 1, confirming our getter implementation.

  4. Now demonstrate the setter functionality by modifying the tween's duration post-creation. Add this code above the console.log() statement:

    var pointerTween = TweenLite.to($pointer, 1, {rotation:"20_cw", transformOrigin:"0px 4px", paused:true, ease:Power1.easeIn});
    
    pointerTween.duration(10);
    console.log("tween duration = " + pointerTween.duration());
  5. Save and preview the page in Chrome.

  6. Hover over the gauge to observe the dramatically slowed animation. The Console now shows: tween duration = 10, demonstrating successful runtime duration modification.

  7. Remove both the duration() method call and console.log() statement to clean up your code.

    The time() method controls the animation's playhead position, offering precise control over which frame of the animation is currently displayed.

  8. Test the time() getter functionality by adding this code below the pointerTween object:

    var pointerTween = TweenLite.to($pointer, 1, {rotation:"20_cw", transformOrigin:"0px 4px", paused:true, ease:Power1.easeIn});
    
    console.log("tween time = " + pointerTween.time());
  9. Save and preview in Chrome. Since the animation hasn't started, the Console displays: tween time = 0

  10. Demonstrate time-based positioning by setting the playhead to mid-animation. Add this code above the console.log() statement:

    var pointerTween = TweenLite.to($pointer, 1, {rotation:"20_cw", transformOrigin:"0px 4px", paused:true, ease:Power1.easeIn});
    
    pointerTween.time(0.5);
    console.log("tween time = " + pointerTween.time());

    This positions the animation exactly 0.5 seconds into its duration upon page load.

  11. Save and preview in Chrome. The page now loads with the pointer already positioned at approximately the third notch, demonstrating precise animation scrubbing capabilities.

  12. Clean up your experimental code by deleting both the time() method call and console.log() statement. This foundational understanding of getter/setter methods prepares us for implementing dynamic animation behaviors.

GSAP Getter vs Setter Methods

FeatureGetter UsageSetter Usage
duration() methodpointerTween.duration()pointerTween.duration(10)
time() methodpointerTween.time()pointerTween.time(0.5)
timeScale() methodpointerTween.timeScale()pointerTween.timeScale(6)
Recommended: timeScale() is most commonly used for dynamic speed control during user interactions.
Understanding time() Method

The time() method sets the playhead position along the timeline. Setting time(0.5) on a 1-second tween positions the animation halfway through its duration when the page loads.

Event Callbacks

Event callbacks represent one of GSAP's most powerful features, enabling custom functions to execute at precise animation moments. Professional developers leverage callbacks to synchronize visual effects, trigger audio, update UI elements, or coordinate complex animation sequences across multiple objects.

The onUpdate callback fires continuously during animation playback, making it ideal for real-time data visualization like our speed display.

  1. Integrate the onUpdate callback into your tween configuration. Modify the tween duration to three seconds for easier testing and add the callback property:

    var pointerTween = TweenLite.to($pointer, 3, {rotation:"20_cw", transformOrigin:"0px 4px", paused:true, ease:Power1.easeIn, onUpdate:showValue});

    The showValue function will execute on every animation frame update, providing smooth real-time feedback.

  2. Create the showValue function to display the current animation time. Add this code around line 81:

    var pointerTween = TweenLite.to($pointer, 3, {rotation:"20_cw", transformOrigin:"0px 4px", paused:true, ease:Power1.easeIn, onUpdate:showValue});
    
    function showValue() {
       console.log(pointerTween.time());
    }
  3. Save and preview in Chrome with the DevTools Console open.

  4. Hover over the gauge while monitoring the Console output. You'll see incremental time values from zero to three seconds, demonstrating the callback's continuous execution during animation.

  5. Move your cursor away to trigger the reverse animation. The Console shows decreasing values from three back to zero, confirming that onUpdate callbacks fire during both forward and reverse playback—a crucial behavior for bidirectional animations.

  6. The progress() method returns a normalized value between 0 (animation start) and 1 (animation complete), providing a percentage-based representation that's ideal for calculating proportional values. A progress value of 0.5 indicates the animation is exactly halfway through its duration.

  7. Replace the time() method with progress() in your console.log() statement:

    console.log(pointerTween.progress());
  8. Save and preview in Chrome with the Console open.

  9. Hover over the gauge to confirm the Console shows values progressing from 0 to 1, with the reverse animation returning to 0. This normalized scale provides the mathematical foundation for our speed calculation.

  10. Locate the displayValue and finalValue variables around lines 73–74. These variables work together to convert our normalized progress into meaningful speed values for user display.
  11. Implement the speed calculation logic by modifying the showValue() function (around line 82):

    function showValue() {
       displayValue = pointerTween.progress() * finalValue;
       console.log(pointerTween.progress());
    }
  12. Test the calculation by updating the console.log() to display our computed value:

    function showValue() {
       displayValue = pointerTween.progress() * finalValue;
       console.log(displayValue);
    }
  13. Save and preview in Chrome with the Console open. The displayed values now range from 0 to 750, but include unwanted decimal precision that clutters the user interface.

  14. Clean up the numerical display by wrapping the calculation in parseInt() to eliminate decimal places:

    function showValue() {
       displayValue = parseInt( pointerTween.progress() * finalValue);
       console.log(displayValue);
    }
  15. This enhanced showValue() function now performs two critical operations:

    • pointerTween.progress() * finalValue converts the normalized progress (0-1) into our target speed range (0-750) through simple multiplication.
    • parseInt() is a standard JavaScript function that truncates decimal values, ensuring clean integer display for better user experience.
  16. Save and preview in Chrome with the Console open.

  17. Test the hover interaction to confirm the Console displays clean integer values from 0 to 750. The reverse interaction should smoothly decrease back to 0, providing consistent bidirectional feedback.

  18. Now transition the numerical feedback from the console to the user interface. Replace the console.log() statement with jQuery's text() method to update the numberDisplay element:

    function showValue() {
       displayValue = parseInt(pointerTween.progress() * finalValue);
       $numberDisplay.text(displayValue);
    }

    The jQuery text() method dynamically updates any DOM element's content, providing seamless real-time updates during animation playback.

  19. Save and preview in your browser.

  20. Test the hover interaction to confirm the numerical display increases from 0 to 750 in sync with the pointer animation. The reverse interaction should decrease smoothly back to 0, creating a polished, professional user experience that rivals commercial animation libraries.

Implementing onUpdate Callback

1

Add Callback to Tween

Include onUpdate:showValue in the tween properties object to trigger the function on every frame update

2

Create showValue Function

Define the custom function that will execute every time the tween updates, whether playing forward or reversing

3

Calculate Display Values

Use progress() method multiplied by finalValue to create meaningful numerical feedback for users

Progress Method Power

The progress() method returns a value between 0 and 1, making it perfect for calculating percentages and proportional values. Multiply by your target maximum for instant user feedback.

Complete TweenLite Callback Arsenal

onStart

Fires when the tween begins playing. Perfect for initialization logic or user interface updates at animation start.

onUpdate

Executes on every frame during animation. Essential for real-time value updates and progress indicators.

onComplete

Triggers when tween reaches its end. Ideal for chaining animations or cleanup operations.

onReverse

Fires when reverse() is called. Useful for handling backward animation states and UI adjustments.

onReverseComplete

Executes when reversed animation finishes. Perfect for resetting states after reverse completion.

Final Implementation Checklist

0/4

Changing a Tween's TimeScale()

The timeScale() method provides dynamic speed control, enabling sophisticated animation timing that responds to user interaction patterns. Professional developers use timeScale adjustments to create engaging micro-interactions—faster reverse animations feel more responsive, while slower forward animations allow users to appreciate visual details.

TimeScale works as a multiplier: 1 represents normal speed, 0.5 halves the playback rate, and 2 doubles it. A tween with a 2-second duration and 0.5 timeScale will complete in 4 seconds, while a 2 timeScale would complete it in 1 second.

  1. Implement accelerated reverse playback by modifying the mouseleave() function (located near the end of your JavaScript, before the closing HTML tags):

    $gauge.mouseleave( function() {
       pointerTween.reverse();
       pointerTween.timeScale(6);
    });

    The timeScale(6) setting makes the reverse animation six times faster than normal, creating a snappy, responsive feel that enhances perceived performance.

  2. Save and test the implementation:
    • Hover over the gauge to confirm the forward animation maintains its 3-second duration at normal speed.
    • Move your cursor away to observe the dramatically accelerated reverse animation—it completes in half a second, providing immediate visual feedback.
    • Hover again and notice the problematic behavior: the forward animation now also plays at 6x speed, creating inconsistent user experience.
  3. Resolve the speed inconsistency by resetting timeScale in the mouseenter() function (around line 86):

    $gauge.mouseenter( function() { 
       pointerTween.play();
       pointerTween.timeScale(1);
    });

    This ensures each hover interaction starts with normal playback speed, regardless of previous timeScale modifications.

  4. Save and conduct comprehensive testing:
    • Confirm the hover animation plays at normal 3-second duration.
    • Verify the reverse animation completes in approximately 0.5 seconds (6x faster).
    • Test multiple hover cycles to ensure consistent speed behavior across interactions.
  5. Return to your code editor to optimize the implementation.

  6. Leverage GSAP's method chaining capabilities to create cleaner, more maintainable code. Combine the animation control and timeScale methods:

    $gauge.mouseenter( function() {
       pointerTween.play().timeScale(1);
    });
    
    $gauge.mouseleave( function() {
       pointerTween.reverse().timeScale(6);
    });
  7. Add click-to-restart functionality for enhanced user control. After the mouseleave() function, implement the click handler:

    $gauge.click( function() {
       pointerTween.restart();
    });
  8. Perform final testing to ensure all interactions work harmoniously:
    • Hover behavior: smooth 3-second forward animation with synchronized numerical feedback.
    • Mouse leave behavior: rapid reverse animation (6x speed) with decreasing numerical values.
    • Multiple hover cycles: consistent timing and behavior across repeated interactions.
    • Click functionality: immediate restart to initial position regardless of current animation state.

    Your implementation now demonstrates professional-grade animation control with multiple interaction patterns, responsive timing adjustments, and real-time user feedback—the hallmarks of modern web animation excellence.

TimeScale Speed Multipliers

Half Speed
0.5
Normal Speed
1
Double Speed
2
Six Times Faster
6

Method Chaining vs Separate Calls

Pros
Cleaner, more readable code with method chaining
Reduces redundant object references
Enables fluent interface programming style
Better performance with fewer function calls
Cons
May be harder to debug individual method calls
Can become complex with many chained methods

TweenLite Event Callbacks

Beyond onUpdate, TweenLite provides four additional callback events that enable comprehensive animation lifecycle management: onStart (fires when animation begins), onReverse (triggers when reverse() is called), onComplete (executes when animation finishes), and onReverseComplete (fires when reverse animation completes). These callbacks enable sophisticated coordination between multiple animations, UI state management, and complex interactive sequences. To explore practical callback implementations and see them in live demonstrations, visit greensock.com/jump-start-js/#event-callbacks

For comprehensive documentation covering all TweenLite methods, properties, and callback events—including advanced configuration options and browser compatibility details—consult the complete API reference at greensock.com/docs/TweenLite

Implementing onUpdate Callback

1

Add Callback to Tween

Include onUpdate:showValue in the tween properties object to trigger the function on every frame update

2

Create showValue Function

Define the custom function that will execute every time the tween updates, whether playing forward or reversing

3

Calculate Display Values

Use progress() method multiplied by finalValue to create meaningful numerical feedback for users

Progress Method Power

The progress() method returns a value between 0 and 1, making it perfect for calculating percentages and proportional values. Multiply by your target maximum for instant user feedback.

Complete TweenLite Callback Arsenal

onStart

Fires when the tween begins playing. Perfect for initialization logic or user interface updates at animation start.

onUpdate

Executes on every frame during animation. Essential for real-time value updates and progress indicators.

onComplete

Triggers when tween reaches its end. Ideal for chaining animations or cleanup operations.

onReverse

Fires when reverse() is called. Useful for handling backward animation states and UI adjustments.

onReverseComplete

Executes when reversed animation finishes. Perfect for resetting states after reverse completion.

Final Implementation Checklist

0/4

Key Takeaways

1GSAP methods like duration(), time(), and timeScale() function as both getters and setters, providing flexible tween control
2The progress() method returns values between 0 and 1, making it ideal for calculating proportional display values
3Event callbacks like onUpdate fire during both forward and reverse animation playback, enabling consistent user feedback
4Method chaining allows combining multiple GSAP methods for cleaner, more readable code
5TimeScale values control animation speed: 1 is normal, 0.5 is half speed, 2 is double speed, and 6 is six times faster
6The parseInt() function removes decimal places to display clean whole numbers in user interfaces
7TweenLite offers five main callbacks: onStart, onUpdate, onComplete, onReverse, and onReverseComplete for comprehensive event handling
8Interactive animations require careful timeScale management to provide different speeds for different user actions

RELATED ARTICLES