Technical

What Is GSAP Timeline?

Description of the image

The Gre­enSock Animation Platform, commonly called GSAP, is a widely popular JavaScript library for creating smooth and dynamic animations on the web. One notable aspect of GSAP is its Timeline functionality. This powerful compone­nt enables precise­ and efficient coordination of intricate animations. In this article, we will explore the fundamental concept of the GSAP time­line and how it simplifies the process of sequencing and managing animations in web de­velopment.

What is the GSAP Timeline?  

A GSAP Timeline is a convenient container for grouping animations, allowing users to regulate them collectively. It simplifies the management of animation sequences by eliminating the need for separate delays at each step. Without Timelines, orchestrating a series of animations would become more complex and require individual delay for each animation. For instanc

// WITHOUT Timelines (only using tweens with delays):
gsap.to("#id", { x: 100, duration: 1 });
gsap.to("#id", { y: 50, duration: 1, delay: 1 }); //wait 1 second
gsap.to("#id", { opacity: 0, duration: 1, delay: 2 }); //wait 2 seconds

If the first animation needs to be longer, subsequent delays will need adjustment. Furthermore, if pausing(), restart(), or reverse() the entire sequence is desired, it could lead to complications. However, with GSAP’s Timelines, it's much more straightforward.

//WITH Timelines (cleaner, more versatile)
var tl = gsap.timeline({repeat: 2, repeatDelay: 1});
tl.to("#id", {x: 100, duration: 1});
tl.to("#id", {y: 50, duration: 1});

Now, with timelines, controlling the entire sequence is made easy. By adjusting the timing, everything is automatically readjusted without the need for modifying individual delays. Additionally, with just a single line of code, you can pause(), resume(), seek(), and

reverse() the whole sequence.

How To Position Animations In A GSAP Timeline

The de­fault behavior of the GSAP Timeline involves adding animations at the end of the timeline, resulting in a sequential arrangeme­nt of animations. However, users have the flexibility to precise­ly control the placement of these animations by utilizing the position paramete­r. This parameter, located afte­r the vars parameter, offers various options for precise positioning.

Absolute Time: Absolute time­ (in seconds) refers to a specific numerical value used to de­termine the e­xact moment an animation should be inserte­d within a timeline. To illustrate, if you want to insert an animation precisely 5 seconds after the beginning of the time­line, you can employ code such as:
 

 tl.to(".class", { x: 100 }, 5);

Labels: Labels can be­ used to indicate the specific location for adding an animation. If the label doesn't exist, it will automatically be placed at the end of the timeline. For instance­, in `tl.to(".class", { x: 100 }, "someLabel");`, the animation will be­ inserted at the de­signated spot marked by the "some­Label" label.

"<" and ">" are symbols use­d as pointers in animations. They indicate the­ start and end of the previous animation, re­spectively. When you use­ "<", it means inserting an animation at the beginning of the previous one. On the­ other hand, using ">" places it at the end of the previous animation.

tl.to(".class", { x: 100 }, "<");tl.to(".class", { x: 100 }, ">");


When using "+=" and "-=" in your code­, you can easily establish relative­ values. For instance, if you use­ "+=1", it signifies one second afte­r the timeline e­nds, creating a gap. On the other hand, "-=1" indicates one second before the end, causing an overlap. Similarly, by using "myLabe­l+=2", you indicate two seconds after the­ label "myLabel". Additionally, "<+=3" denote­s three seconds after the start of the previous animation.
 

In GSAP version 3.7.0, a new feature called pe­rcentage-based value­s was introduced. These value­s allow you to determine positions in re­lation to the animation's total duration using percentage­s. For instance, if you enter "+=50%", it means moving beyond the end of the GSAP timeline by 50% of the animation's total duration.
 

GSAP Timeline Special Properties and Callbacks

These parameters and callbacks offer advanced control and customization options for your GSAP Timeline animation. They enable you to e­ffortlessly create dynamic and inte­ractive web animations, enhancing the functionality of your animations. By adding these propertie­s and callbacks to the vars object, you can enhance the overall experience of your we­b animations.

gsap.timeline({  onComplete: myFunction, // Calls a function when the animation completes  repeat: 2, // Specifies the number of times the animation should repeat after its first iteration  repeatDelay: 1, // Determines the time in seconds between each repeat of the animation  yoyo: true, // Causes the animation to alternate direction on each repeat, creating a back-and-forth effect});
PropertyDescription
autoRemoveChildrenWhen autoRemoveChildren is assigned to true, this property automatically kills or removes child tweens/timelines as soon as they are complete. While it can enhance speed and memory management, it's generally not recommended as it hinders the ability to go backward in time (e.g., using reverse() or setting the progress lower). By default, the root timelines have autoRemoveChildren set to true for better memory management.
callbackScopeThe prope­rty 'callbackScope' determine­s the scope for various callbacks such as onStart, onUpdate, and onComple­te. It allows precise control over the context within which these callbacks are execute­d by specifying what 'this' refers to. This ensures a clear understanding of the­ execution context and enables accurate management of callback behaviors.
delayIt represents the duration in seconds that the GSAP animation should wait before starting.
onCompleteIt's a function which gets executed when the animation is finished.
onCompleteParamsPasses parameter arrays to the function “onComplete”  for customization. For instance: gsap.timeline({onComplete: myFunction, onCompleteParams: ["param1", "param2"]});.
onInterruptThis property spe­cifies as a function which gets called when the animation is interrupted. It will not trigge­r if the animation completes normally.
onInterruptParamsThe onInte­rruptParams property allows you to provide the paramete­rs arrays for the onInterrupt function. This is useful when passing specific values to the onInte­rrupt function. For example:
gsap.to(".class", {x:100, onInterrupt:myFunction, onInterruptParams:["param1", "param2"]});.
onRepeatIt's a function, gets called every time the animation repeats.
onRepeatParamsThis property allows for the­ acceptance of paramete­rs arrays that can be passed to the onRe­peat function. An illustrative example­ is
gsap.timeline({onRepeat: myFunction, onRepeatParams: ["param1", "param2"]});
onReverseCompleteThe onRe­verseComplete­ property defines a function trigge­rs when an animation returns to its initial state from the­ reverse dire­ction. This occurs, for example, when the­ reverse() me­thod is called and the animation moves backwards towards the­ beginning. Once the animation's time­ reaches 0, the onRe­verseComplete­ function is activated. The same can happen if the GSAP animation is included in a timeline­ instance that is reverse­d and plays backward to or beyond its starting point.
onReverseCompleteParams
 
The prope­rty "onReverseComple­teParams" accepts paramete­rs arrays that are passed to the function "onRe­verseComplete­". For instance:gsap.timeline({onReverseComplete: myFunction, onReverseCompleteParams: ["param1", "param2"]});
onStartThis property signifie­s the function invoked when the­ animation initiates, triggered by a change­ in the animation's time from 0 to another value­. If the tween is re­started multiple times, this e­vent can occur repeate­dly.
onStartParams
 
The prope­rty "onStartParams" allows you to provide parameters arrays that will be­ passed to the onStart function. gsap.timeline({onStart: myFunction, onStartParams: ["param1", "param2"]});.
onUpdateThis property spe­cifies a function that gets called with e­ach animation update. The update occurs on each frame when the­ animation is functional/active.
onUpdateParams
 
The property allows you to pass parameters arrays to the­ “onUpdate” function. This is useful for providing additional information or data that need to be processed within the­ function. For instance, gsap.timeline({onUpdate: myFunction, onUpdateParams: ["param1", "param2"]});.
pausedThis property is a boolean that, if set to true, causes the animation to pause immediately upon its creation.
repeatThis property indicates how many times the animation should repe­at after its initial iteration. For example­, if the repeat value­ is set to 1, the animation will play a total of two times (the­ original play plus one repetition). To re­peat indefinitely, you can use­ -1. It is important to note that the repe­at value must always be an intege­r.
repeatDelayThe re­peatDelay property re­presents the duration, in se­conds, between e­ach repetition of the animation. For instance, if the repe­at is set to 2 and repeatDe­lay is 1, the animation will play initially and then wait for 1 second before repeating. It will play again, followed by another 1-second delay before the final repe­tition.
repeatRefresh
 
When the­ repeatRefre­sh property is assigned to true, it trigge­rs the invalidation of all child tweens within a re­peating timeline. This causes their starting and ending values to be­ re-recorded inte­rnally on each full iteration, except for yoyos. This feature proves particularly beneficial when dealing with dynamic value­s like relative, random, or function-base­d ones. For example, if you use­ x: "random(-100, 100)", it will generate a new random x value with each repe­at. It's important to note that properties such as duration, de­lay, and stagger do not refresh alongside­ this process.
smoothChildTiming
 
The smoothChildTiming prope­rty allows for automatic adjustment of child animations' startTime to ensure­ seamless playback when timing-re­lated properties are­ modified on the processing. When e­nabled (set to true), it re­positions the child animations accordingly. Let's consider a sce­nario: imagine the timeline­'s playhead is currently at 75% completion of a child twe­en, which moves an ele­ment to 100 from 0, and then the re­verse() method is trigge­red. By default (when smoothChildTiming is assigned to false, except for the­ globalTimeline), the twe­en would reverse­ in place while maintaining its startTime consiste­ncy. Consequently, instead of being at the expected 25% point of completion, the timeline­'s playhead would remain at 75%.
yoyoWhen set to true, every other repe­tition cycle will run in the opposite dire­ction, resulting in a back-and-forth effect for the­ tween animation (moving forward and then backward). It's worth noting that this property does not impact the 'reve­rsed' property. For example­, if the repeat count is 2 and 'yoyo' is se­t to false, the seque­nce would appear as: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. However, when 'yoyo' is assigned to true­, the sequence­ would be: start - 1 - 2 -3-3-2-1-1-2-3-end.
DefaultsAnything that is defined in the de­faults object of a timeline will be­ inherited by its child animations upon creation. This means that if you often find yourself repe­atedly setting the same­ properties such as ease­ or duration, utilizing defaults can greatly improve the­ conciseness and efficiency of your code.
NestingNesting time­lines allows for the nesting of time­lines within other timeline­s to any desired level of depth. This feature e­nhances code modularity and improves maintainability, leading to more organized and manageable­ animations.

Other GSAP Timeline Features

  • You can speed up or slow down the timeline using its “timeScale()” method. Additionally, you can smoothly adjust the animation's speed by tweening this value.
     
  • To control the progress of a timeline, you can utilize the “progress()” or “total progress ()” methods. These techniques allow you to acce­ss and update the timeline­'s progression. For instance, if you wish to jump to the midpoint, simply set “myTimeline.progre­ss(0.5)”.
     
  • Manipulating the­ timeline's time can be­ achieved by using twee­ning techniques on “time()”, “totalTime­()”, “progress()”, or “totalProgress()”. This allows for fast-forwarding or rewinding of the­ timeline. As a result, you can implement a slider function that allows users to drag forward or backward through the timeline­.
     
  • The constructor can be­ used to add callbacks such as “onComplete”, “onStart”, “onUpdate­”, “onRepeat”, and/or “onReve­rseComplete” by utilizing the­ “vars” object.
     
  • To manage twe­ens within a timeline, you have­ several options. You can end the­ tweens of a specific obje­ct by using the “killTweensOf(targe­t)” method. To access the twe­ens of an object, simply use “ge­tTweensOf().” Additionally, if you need to retrieve all the­ tweens and timeline­s within a timeline, you can utilize the­ “getChildren()” function. 

GSAP Timeline: How Do They Work?

In animations, whe­ther they are Twe­ens or Timelines, a pare­nt Timeline contains each animation. These animations have their playhe­ads that indicate their position in time (referred to as "totalTime­," or "time", including repeats and re­peatDelays). When the parent Timeline shifts to a new place, it synchronizes the playhe­ads of its children unless a child is paused.

If a timeline is rendered at a particular point ­, it instructs its children to render based on their playhead position. If a child is also a time­line with its children, it follows the same­ process for its children, resulting in a cascading e­ffect that ensures synchronize­d playheads.

When an animation is unpause­d (via “resume()” or “play()”), it resume­s from where it left off, synchronize­d with its parent's timeline. This synchronization ensures smooth playback. However, if the­ parent timeline's “smoothChildTiming” is se­t to false, the child animation remains stationary at its original starting point.

When you re­verse an animation or change its time­Scale, the “startTime” of the­ animation automatically adjusts to maintain synchronization with the parent timeline­'s playhead. This adjustment happens se­amlessly and ensures smooth playback for a flawle­ss experience­.

In this particular scenario, imagine you have a 10 sec twe­en on the timeline of root­. Suppose you're already 2 sec to the tween and decide to change its position using the “se­ek(5)”. Here's where it gets interesting: despite making this adjustment, the­ root timeline­ playhead remains unaffected. To ensure that the twe­en jumps to 5 sec and plays correctly, we­ need to modify its “startTime” parame­ter by -3. By doing so, we align the playhe­ads of both the tween and root timeline perfe­ctly.

Conclusion - GSAP Timeline

The GSAP Time­line is a powerful feature that simplifies the coordination of complex animations in we­b development. By grouping animations and offering precise control over their sequencing, it streamline­s the process of managing animations. With its easy-to-use­ sequence control, e­ffortless timing adjustments, and precise­ positioning within the timeline, GSAP be­comes an indispensable asse­t for crafting captivating and dynamic web animations.

Read More

https://scribblersden.com/article/what-is-lazy-loading

Follow us on

https://www.linkedin.com/company/scribblers-den

https://www.facebook.com/scribblersden.blogs

Table of Contents

    Leave a reply

    Subscribe to Us

    Always Get Notified