08 September 2022
GSAP library – JavaScript animation tutorial. An elegant way to add awesome animations to your project
If there only was a way to create impressive JavaScript animations easily and without having to worry about browser compatibility… oh wait, there is one! Or perhaps more than one. Today, you’ll see how to develop such animations with the GreenSock Animation Platform, or GSAP. Why did I choose this one? How does it really work? What can it do for you? Let’s find out.
Have you ever worked on a project which required you to create complex animations in a JavaScript application that relies on frequent user interactions?
I just have. Today I’m going to tell you more about a tool that made this experience much more interesting.
The challenge
My latest experience with JavaScript animations came about when one of our clients asked my team to develop a new feature for their highly secure application. It was supposed to be something akin to a lock screen.
If you ever used a banking application in your life, you definitely recognize the screen that shows up when you are logged out of your session due to a period of inactivity.
This one worked much like that, except for one small detail.
The difference was that instead of being logged out entirely, you get a lock screen with an option to go back to the app by writing your PIN number.
I admit that in practice, it amounts to pretty much the same thing for the user. From a technical standpoint, it is a different behavior as you don’t need to type in your full credentials.
Aside from security, the client greatly valued another aspect of their app – its appearance. The project was designed with great care and attention to detail. It included complex and well–optimized animations. The lock screen was to be no different.
What does it mean?
It means that I needed to come up with some really nice-looking JavaScript animations!
Why the GSAP library?
JavaScript-based animations are not an easy subject. The first thing that came to my mind was to find a library that could make the development faster. Taking care of countless browser inconsistencies in rendering JS animations was another important objective. Long story short, I picked the GreenSock Animation Platform (GSAP). 🧦
GSAP is a powerful JavaScript library and a robust JavaScript toolset that makes it easier to create professional grade animation. You can use it to design all kinds of JS animations, ranging from simple manipulations of individual DOM elements to complex effects that involve multiple segments triggered at specific moments. Such effects include:
- Progressively revealing or hiding SVG strokes to achieve the effect of drawing in real-time (the DrawSVGPlugin plugin).
- Turning (morphing) one SVG shape into another smoothly (MorphSVGPlugin).
- Moving generic objects along a predetermined path (MotionPathPlugin).
GSAP gives you precise control over CSS properties, making it possible to create professional grade animations. It also provides advanced playback controls and accessibility friendly animations. This particular library met the requirements of the project best of all available options for a couple of reasons:
- It makes it possible to implement all types of animations that were relevant to the project.
- It can animate anything JavaScript, that is, any numerical property of JavaScript or a given object.
- GSAP is so comprehensive that it can animate any CSS/JS property supported by a given browser.
- And then, there is the community. The authors created a discussion forum that over time produced a larger user base. It’s really vibrant, full of people willing and able to help.
- And considering the popularity of GSAP, there aren’t that many issues you may come across that were not already addressed before.
You can add GSAP to your project in various ways – by uploading local files, through npm, or by using CDN (“cdnjs.cloudflare.com ajax libs gsap”).
GSAP animations were not the only alternative I considered.
GSAP alternatives
Another solution I considered is anime.js. It might have great potential, but its problem is the lack of continuous support for the library. The software has not been updated for almost 2 years. And while it still works just fine, and there is no clear indication that the library was abandoned, I can’t help but be wary of that situation.
When working on large and scalable systems, such as the one I’m tackling in this case study, you need to have full confidence in all the third-party solutions you use.
In that regard, GSAP was a clear winner when compared to alternatives such as anime.js or Animate css.
Useful GSAP resources
As I said, GSAP provides a lot of resources that make your introduction to the library smoother. I highly recommend you try these:
- The documentation is very detailed and full of interactive examples.
- The aforementioned forum has almost 119k posts (as of August 2022) in the general subforum alone!
- Using GSAP with React is thoroughly covered.
- So are the common GSAP mistakes so that you don’t have to make them yourself.
Alright! With that said, I guess we can finally take a look at the library itself.
How does GSAP work? GSAP tutorial
Before I get back to the project, I’m going to give you a quick overview of the theory so that you can create animations like this yourself.
Theory
The tween
When you start with GSAP, one of the first concepts you learn about is the tween. This is the building block of any GSAP-based work.
The tween is one unit of animation. You can initiate it in three ways:
- gsap.to() – all you determine are the ending CSS values your object is to be animated into.
- gsap.fromTo() – you determine both starting and ending CSS values of your animations.
- gsap.from() – you only determine starting values (the ending values will be inherited from default CSS styles).
I sorted the list above, starting from those that I feel are used the most for tweens.
Let’s take a look at an example of a tween based on the gsap.to() function.
A HTML element is the first argument of the function. To do the same in React, you will typically turn to useRef. In addition to the element itself, you can also reference an ID or HTML class. That gives you plenty of options to get to elements in which adding a ref is difficult. A good example of such elements could be SVGs imported from assets and used as regular React components.
The second argument used here is a selection of animation properties. The complete list of properties obviously includes all of the CSS properties. In addition, GSAP offers a lot of custom properties. It also includes callbacks, which serve as something of a bridge between the world of animation and JavaScript. Thanks to callbacks, animation events can trigger some secondary effects.
One of the most interesting and most used properties is autoAlpha. When set to 0, it combines the effects of opacity set to 0 and visibility set to hidden.
Timeline animations
Let’s say you want to develop a more complex animation with GSAP. You should start by learning more about timeline animation, which is essentially a cluster of tweens. GSAP makes it possible to use advanced sequencing in a timeline to achieve great control over individual tweens. Let’s take a look at an example of such advanced sequencing.
Let’s modify the previous example by breaking it into two separate stages. Each stage is a separate tween and the whole piece of code is a timeline.
Not too hard, isn’t it?
You might have noticed an additional argument in the last tween – +=0.5. When you use tweens inside of a timeline, you can add time modifiers. The one above means that the animation will execute half a second after the previous one is completed.
Are your animations accessible? Find out in this animation accessibility guide.
Back to the project – a practical GSAP case study
That’s it for the basic theory. At this point, you should be more than familiar enough with GSAP to dive deeper into my project. To make it a little easier, still, let’s put aside the issue of security and focus entirely on the animations.
But what kind of animation tutorial would it be without something for you to click at? To make it more interesting, I prepared a live animation example in CodeSandbox. I highly encourage you to play with it a bit.
In a real project, I use the GSAP package. This time, I’ll use the gsap-trial package that’s only intended for experimentation. It includes various bonus files, some of which you normally need to pay for. I’ll get back to the subject of plugins later. For now, let’s focus on the code.
In this simplified example, the screen is blocked when you click the button.
The mechanism is as follows:
- When you click the button, you trigger the animation.
- The curtains show up.
- Then, the padlock locks.
- The keyhole turns red.
- In order to unlock it, you click the padlock again.
- The animation is triggered again, but it is now in reverse.
The entire process takes place inside the ScreenLocker component.
For starters, you need to declare your refs and then insert them into proper tags.
Inside my ref, I put not only my HTML and SVG elements, but the timeline as well. Thanks to that, it won’t have to be created multiple times when the component’s logic gets more complex. The timeline is set to paused by default so that it doesn’t launch right after it is defined.
Next, I need to set the initial values of all elements. It’s important to do it at the start to have only one source of truth regarding these values. I really can’t stress enough just how important it is. Oftentimes, one of my teammates would set a CSS value, would NOT tell anyone about this, and then forget about the whole thing the next day. And then – the animation misbehaves and nobody knows why. A single source of truth (in time and in the flesh) really does make a difference.
I need to make sure that my refs are not null during the initialization.
Then, I can set all the required properties. As you can see in the last gsap.set, the values are not limited to strings and numbers. A function is another common option. You can use it to execute some calculations based on other sources.
As you can see, an array of elements is also allowed. It gives you even more options. For example, you can set different values depending on whether the array element is odd or even.
In this example, the curtain is to move to the left for the first element (index=0) and then to the right for the second element (index=1).
Now, I’m going to implement the lock screen timeline.
It’s vital for the useEffect or useLayoutEffect hooks, in which I defined the timeline, to execute only once. Otherwise, each subsequent callback execution will cause the timelines to stack up.
The timeline consists of five tweens:
- The curtains move inwards.
- Simultaneously (thanks to the < modifier), the padlock shows up.
- 0,2 second after the previous tween concludes, the padlock handle goes back to the closed position and then bounces back slightly, simulating how a padlock typically closes. This rebounding effect is created with the back.in(3) easing.
- Finally, the keyhole turns red to indicate that the screen is now locked.
The useEffect hook contains more information on the behavior of the timeline:
In case of problems with React 18 and timelines stacking up in the dev mode, it’s recommended to turn off the StrictMode.
And that’s it for the project! Once you know all the basics, you will be well equipped to make animations such as those I showed you. And whenever you run into trouble, you should take a look at the docs. It’s very comprehensive and even includes a common mistakes section. If you ever spent any meaningful time trying to make a JavaScript animation work, you will certainly appreciate it.
Extend GSAP capabilities with plugins
This tutorial would not be complete without a word or two about plugins. After all, while I deliberately did not use them in my simple example, they are an extremely important and useful aspect of using GSAP in practice.
There are two plugins that I find particularly interesting:
ScrollTrigger
This appropriately named GSAP plugin makes it possible to trigger certain animations and callbacks when you execute corresponding scroll events. For example, when you scroll your way into a specific area of your app, leave it, or enter it from the top.
Draggable
Another practical plugin is Draggable. And it’s another one that got a highly appropriate name, as it specializes in producing the dragging effect for HTML elements. All it takes is a short bit of code:
With this simple hook, you can make each HTML element draggable. Here is how you can use it in practice:
The hook returns a ref, which you can insert into the element of your HTML file.
That’s the gist of it. Of course, you can expand this concept by changing how the draggable effect is supposed to work. You can use it:
- On the X-axis.
- On the Y-axis.
- Or by rotating a single element.
Draggable works well with the paid Inertia plugin. When combined together, you can enrich the dragging effect with impressive finishes, such as having an element glide to a stop in a smooth way. You can test it with gsap-trial.
Lessons learned – why and when to use the GSAP library
GSAP has a lot of benefits:
- It’s really intuitive and easy to use.
- The animations made with GSAP are well-optimized out-of-the-box.
- The community is big and really helpful.
- The docs is a real standout.
However, that doesn’t mean that GSAP is the best choice for every project.
Use it for apps that require multiple elements, high performance animations, the need for motion paths, and anything else that enables front end developers to achieve advanced effects easily.
I would not recommend it for apps that only sport the most basic animations. In such projects, the overhead caused by including GSAP will not be worth the contribution it makes. After all, a library as robust and powerful as this one has to weigh a bit. In the case of GSAP, the weight is about 60kB when minified and 25kB when minified and gzipped. And that’s for the basic version without plugins. It’s somewhat comparable to the JavaScript utility library Lodash.
In addition to that, for simple animations, the amount of code generated with GSAP might be bigger than with pure CSS.
If all you want is to add a couple of basic effects, you really need to analyze if adding such a dependency is a good idea.
Other than that, GSAP really does deliver on its promises, providing you with impressive and well-optimized animations for your custom software project. It’s also really fun to use.
But don’t take me at my word – try the GSAP sandbox and find out for yourself!
JavaScript animations are one of the most interesting JS trends. Are you looking for more of them?
You can find them in our latest State of Frontend 2022 report, contributed to by +3700 surveyed specialists from 125 countries.