Eye-Catching Animations with GreenSock

Tweet

Eye-catching website animations can really grab attention and help increase conversions. Unfortunately, animations are never easy to create. Website developers spend many hours designing, reviewing, and revising their animations before turning them loose on the world. While many developers use the Adobe Flash platform to simplify the arduous task of tweening objects on a timeline, the lack of Flash support on mobile devices has many developers turning to JavaScript.

To support the increasing demand for JavaScript animation, software vendors have created some amazing development tools. One of these vendors, GreenSock, provides some very useful and mature tools for tweening objects and putting them on a timeline. These tools are mature because GreenSock is not new to this business; they have created — and continue to create — animation tools for Flash ActionScript, and they have ported these tools to support JavaScript.

In this article, I’ll briefly describe the GreenSock tools for tweening and timeline construction.

A Brief Introduction to Tweening on a Timeline

Animation developers use “tweening” to fill in frames of animation between two points in time. (The word “tween” is derived from the word “between.”) For example, when a developer wishes to animate a ball rolling from point A to point B, she need only draw a picture of the ball at each endpoint and let the computer fill in the frames between.

Animation developers use timelines to move their animations along. For example, the developer specifies precisely when the ball gets released from point A and when it arrives at point B. Additionally, the developer uses an “easing” function to govern how the ball accelerates and decelerates along its path. Easing gives the appearance that the ball conforms to familiar laws of physics.

Tweening on a timeline can get very complicated, especially when there are several objects moving around the screen, each with its own path, speed, and timeline. It gets even more complicated when revisions need to be incorporated after the design review. It turns out that it’s far easier to revise tweens and timelines programmatically rather than graphically. In other words, instead of arduously redrawing frames with revision, you simply change some of the numeric variables.

The GreenSock Tools

There are four main animation libraries from GreenSock: TimelineLite, TimelineMax, TweenLite and TweenMax. The “Max” versions extend the “Lite” versions in an object-oriented way, providing more functionality at the price of a slightly larger file size. You can generally use these libraries for free; however, I recommend purchasing a licensed tier and becoming a part of “Club GreenSock.” This provides you with the latest beta versions as well as some cool extensions. Also, your license applies to both the JavaScript and ActionScript versions.

The names of the GreenSock libraries are self-explanatory: The “Tween” libraries allow you to tween visible elements around the screen, and the “Timeline” libraries allow you create independent timelines on groups of objects. Note that an object can be a part of more than one timeline.

Let’s look at a simple example to see how tweening on a timeline works with the GreenSock tools.

Raining Letters

We’ll set up a simple animation where each letter from the phrase, “Tweening on a Timeline” independently falls into view, bounces and then settles into place. First, we set the stage with the following HTML file.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Tweening on a Timeline</title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script src="js/raining.js"></script>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="stage">
      <div id="raining-text">Tweening on a Timeline</div>
    </div>
  </body>
</html>

Notice the inclusion of the GreenSock tool, TweenMax, on line 6. This externally referenced file contains most of the major GreenSock libraries, including the Timeline files and some ancillary libraries. In your own applications, you should load these libraries from a local directory, and only load the libraries you need. Everything was loaded in this example for the sake of simplicity.

Also note that we load the jQuery library on line 7. The GreenSock tools do not need jQuery at all. However, if you happen to load jQuery, GreenSock plays very nicely with it.

Line 8 shows the loading of the local raining.js file. This is the file that will control the animation, and we’ll look at it more closely later.

Finally, notice that the body contains the stage and raining-text elements. The stage is the window within which the animation takes place, and the raining-text element holds the phrase that will be animated.

Next, we style everything with the style.css file:

@charset "UTF-8";
#stage {
  background-color: #000000;
  width: 600px;
  height: 250px;
  position: relative;
  margin-top: 20px;
  overflow: hidden;
}

#raining-text {
  color: #ffffff;
  font-family: Arial, sans-serif;
  font-size:24px;
  position: absolute;
  bottom: 5px;
  width: 100%;
  text-align: center;
}

There are a few things to notice in this CSS file. First, the stage uses relative positioning. This allows for easier positioning of absolutely positioned elements contained within. Secondly, the stage overflow is hidden; this prevents your animations from interfering with elements outside the stage. Finally, the raining text position is set by the bottom attribute. This attribute will be manipulated in the animation.

Now, let’s have a look at the raining.js file, where all the action takes place.

// Sample script for Tweening on a Timeline
$(function() {
  var rainingPhrase = $("#raining-text");
  var tl = new TimelineLite();

  tl.add(TweenLite.set(rainingPhrase, {bottom: 250}));
  tl.add(TweenLite.to(rainingPhrase, 2, {bottom:5, ease: Bounce.easeOut}));
});

On line 3, we use jQuery to create a selector, rainingPhrase, for the raining text. As mentioned before, GreenSock does not depend on jQuery, but it can use jQuery if it’s available.

On line 5, we create a timeline and reference it with the variable tl. A GreenSock timeline is used to group individual actions in sequential order. In this case, we create two actions: 1) Set the phrase above the stage, where it will be hidden by the overflow attribute, and 2) drop the text to the bottom of the stage.

Let’s look at the first action on line 6. We create a tween by instantiating a new TweenLite object and then using the set class function on that object. The object itself is the first argument, and the object within the second argument specifies the manipulation. In this case, we’re setting the bottom attribute of the rainingPhrase object such that it gets moved above the stage. The set function essentially manipulates an object instantly, with no motion.

What’s the purpose of tweening if we’re just moving something instantly? Well, if there’s a problem loading or running the GreenSock library, the original raining text will not be moved from its original position. Basically, we position the text within the stage at a place that makes sense if, for some reason, the animation fails to run.

The visible action takes place on line 7. Because the tween in this line was added to the timeline after the tween on line 6, it will not execute until the previous tween has completed. Note that this isn’t necessarily always the case; we could use a “negative delay” attribute in this tween to have it act upon the target object before the preceding tween completes its action. In this case, however, we want the previous tween to run to completion.

The tween on line 7 is instantiated and immediately runs the to class function. This function essentially says, “manipulate an object FROM its current state TO a target state.” The object itself is specified as the first argument, the duration of the action (in seconds) is specified in the second argument, and the third argument specifies the type of manipulation. Note that the manipulation can contain virtually any CSS attribute such as scale, rotation, color, etc. In this case, the manipulation specifies that the object will be moved to the bottom of the stage.

Rather than sliding the object to the bottom of the stage in a linear fashion, the easing function throws a bit of fun into the animation. By specifying the easing function as Bounce.easeOut, we tell the system to simulate a bouncing ball when implementing the animation.

If you run the program, you’ll see that when the page loads, the entire phrase initially appears at the top of the stage and then accelerates toward the bottom. When it hits the bottom, it bounces a few times before coming to rest. Cool, yes?

There’s a problem, however. I haven’t delivered on my promise to have each character independently fall and bounce into place. Instead, the whole phrase falls and bounces as a single unit. It’s an interesting animation, but we need to spice it up a bit.

The problem is that we need to break up the phrase into individual characters. This could be a lot of work. If you were to do it the hard way, you’d have to split the phrase into individual non-blocking div elements, load each div into a timeline and hope it drops into place so that it looks like the original phrase. Imagine doing all this coding, only to find out that the marketing department wants to change the phrase to something else, like “A Timeline with Tweens.”

Fortunately, there’s an easy solution. It’s called SplitText. If you’re a member of Club GreenSock, you get access to a nice plugin file called SplitText.min.js. SplitText takes a reference to your text string and splits it into individual characters and then loads them into an array. You can then use the array with the TimelineLite stagger function, which will automatically build an independent timeline for each SplitText object.

Let’s see how this works.

First, put the SplitText.min.js file into the JavaScript directory and then reference it within the HTML file as shown on line 7 below.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Tweening on a Timeline</title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
    <script src="js/SplitText.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script src="js/raining.js"></script>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="stage">
      <div id="raining-text">Tweening on a Timeline</div>
    </div>
  </body>
</html>

Note that SplitText automatically finds the text element without the help of jQuery, so you could remove your reference to it on line 8. The only problem is that you’ll have to use a different “document ready” function, rather than the $(function(){}) function used in raining.js.

Now let’s look at the really cool part. We can actually split the text, preset it above the stage and drop the individual characters onto the stage in just four lines of JavaScript code! Open up raining.js and change it as shown below.

// Sample script for Tweening on a Timeline
$(function() {
  var splitPhrase = new SplitText("#raining-text", {type: "chars"});
  var tl = new TimelineLite();

  tl.staggerTo(splitPhrase.chars, 0, {bottom: 250}, 0);
  tl.staggerTo(splitPhrase.chars, 2, {bottom: 5, ease: Bounce.easeOut}, 0.02);
});

In this code, we create a reference to the split text on line 3. The SplitText object takes two arguments: the reference to the text and the type of splitting to perform on that text. In this case, we split on characters, though we could also split on lines and words, or a combination of all three. The splitPhrase variable now contains an array of characters, which we’ll reference soon.

We build the timeline on line 4 exactly as we did earlier in this article.

Line 5 uses a TimelineLite function called staggerTo. This function takes an array of objects as its first argument and builds individual timelines and tweens for each object. The second argument provides a duration value — in this case, we want instantaneous action, so we set its duration to zero. (Keep in mind that we’re pre-positioning the characters above the stage.) The third argument contains the “to” manipulation to perform on each object in the array, and the fourth argument specifies the amount of time to stagger each object’s timeline.

Line 6 is where all the action takes place. It looks exactly like line 5, except the arguments have been changed. In this case, we move all characters to the bottom of the stage over a two second duration, staggering them by 0.02 seconds, and use an easing function that simulates a bounce.

title

Conclusion

Website animation can really catch the eye and help convert visitors into customers. But it’s never easy to create these animations. You must use JavaScript to ensure your animations render across all devices, from desktop to mobile. A number of vendors are creating JavaScript tools to help with this process. This article focused on the GreenSock tools. Using GreenSock’s timeline and tweening tools, you can quickly create animations with realistic easing functions, and because these tools run in code, it’s easy to implement revisions. In this article, we created a simple example where we split a phrase into characters and dropped them one at a time onto the stage, where they came back together as a phrase. And we accomplished most of this action in just four lines of code!

Edited: The fine folks at GreenSock sent us this CodePen to complement the article.

See the Pen Demo made to compliment SitePoint article by GreenSock (@GreenSock) on CodePen.

Free JavaScript: Novice to Ninja Sample

Get a free 32-page chapter of JavaScript: Novice to Ninja and receive updates on exclusive offers from SitePoint.

No Reader comments