Back to JavaScript
2026-01-207 min read

Explicit Animations (JavaScript)

Learn Explicit Animations (JavaScript) step by step with clear examples and exercises.

Why This Matters

In this extensive guide, we delve into the world of JavaScript animations, focusing on explicit animations - a technique that offers greater control and performance benefits over implicit animations (such as CSS transitions and transforms). We'll explore why explicit animations matter, their prerequisites, core concepts, worked examples, common mistakes, practice questions, and frequently asked questions.

Why This Matters

Explicit animations are essential for creating complex, customizable, and high-performance animations in JavaScript applications. They provide greater control over the animation lifecycle, allowing developers to fine-tune properties like easing functions, frame rate, and callbacks. This makes them an indispensable skill for building interactive user interfaces and engaging web experiences.

Prerequisites

To follow this tutorial, you should have a good understanding of:

  1. JavaScript fundamentals (variables, functions, loops, arrays)
  2. DOM manipulation (selecting and modifying elements)
  3. Event handling (responding to user interactions)
  4. RequestAnimationFrame (for smooth animation updates)
  5. Understanding the basics of CSS properties like position, transform, and opacity
  6. Familiarity with browser APIs such as window.innerWidth and document.querySelectorAll()
  7. Basic understanding of CSS units (pixels, percentages, ems, etc.)
  8. Knowledge of the Document Object Model (DOM) and how it relates to JavaScript
  9. Familiarity with asynchronous JavaScript concepts like promises and async/await
  10. Understanding of event delegation for efficient event handling

Core Concept

Framework Overview

We'll be using the popular GSAP library (GreenSock Animation Platform), which simplifies creating high-quality animations and transitions in JavaScript. It provides a set of powerful tools, including TweenLite (for single-property animations) and TimelineMax (for chaining multiple animations).

Creating an Explicit Animation

  1. Include the GSAP library in your HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.8.0/gsap.min.js"></script>
  1. Select the DOM element you want to animate using JavaScript.
  2. Create a new TweenLite instance, specifying the target property, its initial and final values, duration, easing function (optional), and callbacks (optional).
  3. Call tween.play() to start the animation.
  4. Optionally, chain multiple animations using TimelineMax or add them to a timeline for synchronous execution.

Example: Animated Box Movement

// Select the box element
const box = document.querySelector('.box');

// Create a new TweenLite instance for moving the box
const tween = gsap.to(box, { x: 300, duration: 2, ease: 'power2.out' });

// Start the animation
tween.play();

Creating Custom Easing Functions with GSAP

GSAP allows you to create custom easing functions using a simple equation-based approach or by interpolating between existing easing functions. This gives you even more control over the motion of your animations.

Using ScrollTrigger for Scroll-Based Animations

ScrollTrigger is a plugin provided by GSAP that enables animations to be triggered based on scroll position, making it easy to create engaging scroll-based experiences.

Worked Example

Let's create an interactive banner with a rotating logo and sliding text. We'll use GSAP's TimelineMax to chain multiple animations together.

  1. Create HTML structure:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Include GSAP library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.8.0/gsap.min.js"></script>
<!-- Include ScrollTrigger plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.8.0/ScrollTrigger.min.js"></script>
</head>
<body>
<div class="banner">
<img src="logo.png" alt="Logo" class="logo">
<h1 class="title">Welcome to Our Banner!</h1>
<p class="description">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
<script src="banner.js"></script>
</body>
</html>
  1. In banner.js, create the TimelineMax instance and define animations for the logo rotation and text sliding:
const banner = document.querySelector('.banner');
const logo = banner.querySelector('.logo');
const title = banner.querySelector('.title');
const description = banner.querySelector('.description');

// Create a new TimelineMax instance with repeat and yoyo options
const timeline = new TimelineMax({ repeat: -1, yoyo: true });

// Define animations for logo rotation and text sliding
timeline.to(logo, 2, { rotation: 360 })
.to(title, 1, { y: -50, opacity: 0 }, 'rotate')
.to(description, 1, { y: 50, opacity: 0 }, 'rotate');

// Add scroll trigger for animations
const logoTrigger = ScrollTrigger.create({
trigger: logo,
start: 'top top' // or any other scroll position
});
const titleTrigger = ScrollTrigger.create({
trigger: title,
start: 'top top',
onEnter: () => timeline.play(),
onLeaveBack: () => timeline.reverse()
});
const descriptionTrigger = ScrollTrigger.create({
trigger: description,
start: 'top top',
onEnter: () => timeline.play(),
onLeaveBack: () => timeline.reverse()
});

Common Mistakes

  1. Forgetting to include the GSAP library in your HTML file.
  2. Not defining the duration, easing functions, or callbacks for animations, resulting in abrupt movement or unwanted behavior after completion.
  3. Using setInterval or setTimeout instead of RequestAnimationFrame, causing performance issues and inconsistent animation frames.
  4. Failing to chain animations using TimelineMax, leading to separate animations running at the same time.
  5. Not clearing previous tweens before creating new ones, resulting in unwanted animation stacking.
  6. Using excessive DOM manipulations during animation updates, which can negatively impact performance.
  7. Ignoring browser compatibility issues when using advanced GSAP features like DrawSVGPlugin or ScrollTrigger.
  8. Not optimizing animations for mobile devices by considering touch events and device capabilities.
  9. Forgetting to account for user preferences (such as high contrast mode) when designing animations.
  10. Using complex custom easing functions unnecessarily, which can make the animation harder to understand or control.
  11. Not testing animations on various devices and browsers to ensure compatibility and performance.

Subheadings under Common Mistakes:

  • Optimizing for Mobile Devices
  • Accounting for User Preferences
  • Simplifying Custom Easing Functions
  • Testing Cross-Browser Compatibility

Practice Questions

  1. Create an animation that scales a box from 0 to 300 pixels on click, using TweenLite.
  2. Animate a text element's color change from red to blue when hovering over it, using TweenMax.
  3. Create a simple loading spinner using GSAP's DrawSVGPlugin, with customizable colors and size.
  4. Implement a scroll-triggered parallax effect for an image and text box, using ScrollTrigger.
  5. Create an interactive carousel with multiple slides that can be navigated using buttons or keyboard input, using TimelineMax.
  6. Animate the resizing of a container element to fit its content, while maintaining aspect ratio, using TweenLite.
  7. Implement a custom easing function in GSAP and use it in an animation, demonstrating how it affects movement.
  8. Create a bouncing ball animation that follows the user's mouse cursor, using ScrollTrigger for mobile compatibility.
  9. Design a responsive modal with smooth opening and closing animations, using TweenMax and ScrollTrigger.
  10. Implement a "stagger" effect where multiple elements animate one after another, using TimelineMax and the staggerFrom method.

FAQ

What is the difference between implicit and explicit animations in JavaScript?

Implicit animations use CSS properties like transition and transform, while explicit animations rely on JavaScript libraries like GSAP to create custom animations. Explicit animations offer more control over the animation lifecycle.

Why should I use RequestAnimationFrame instead of setInterval for animations?

RequestAnimationFrame is optimized for smooth animation updates by synchronizing with the browser's repaint cycle, reducing CPU usage and ensuring consistent frame rates.

How can I create a custom easing function in GSAP?

You can create a custom easing function using the Ease class provided by GSAP. For example:

const CustomEase = new Ease(0, 0, 1, 1, 0.5);

How do I control the speed of an animation in GSAP?

You can adjust the duration of an animation by passing a number representing the desired time (in seconds) to the to method. For example:

gsap.to(box, { x: 300, duration: 4 });

What are some common performance considerations when creating animations in JavaScript?

Some key performance considerations include minimizing DOM manipulations, reducing the number of tweens running at once, using efficient easing functions, and optimizing animation updates with RequestAnimationFrame. Additionally, it's important to account for browser compatibility issues and mobile device capabilities.

How do I create a looping animation in GSAP?

You can use the repeat and yoyo options when creating a TweenLite or TimelineMax instance to create a looping animation. For example:

const timeline = new TimelineMax({ repeat: -1, yoyo: true });
// ... define animations here
timeline.play();

How do I create a scroll-triggered animation in GSAP?

You can use ScrollTrigger to create animations that are triggered based on scroll position. First, include the ScrollTrigger plugin in your HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.8.0/ScrollTrigger.min.js"></script>

Then, define a ScrollTrigger instance and create animations for the corresponding trigger elements:

const scrollTrigger = ScrollTrigger.create({
trigger: '.element',
start: 'top top' // or any other scroll position
});

// Define animations for the triggered element
gsap.to('.element', { /* ... animation properties here ... */ });

How do I create a custom easing function in GSAP using the equation-based approach?

You can define a custom easing function by creating an array of keyframes and passing it to the Ease.create() method. For example:

const ease = Ease.create([0, 0, 1, 1, 0.25]);

How do I create a custom easing function in GSAP using interpolation between existing easings?

You can create a custom easing function by combining two or more existing easings with the Ease.interpolate() method. For example:

const ease = Ease.interpolate([{ type: 'easeOut', ease: 'power2' }, { type: 'easeIn', ease: 'back' }]);

How do I create a custom easing function in GSAP using the Easing class?

You can define a custom easing function by extending the Easing class and overriding the getRatio() method. For example:

class CustomEase extends Easing {
static get INITIALIZER(params) {
this._value = params[0];
this._duration = params[1];
}

getRatio(ratio) {
const value = this._value * Math.pow(2, 10 * (ratio - 1));
return value / this._duration;
}
}
Explicit Animations (JavaScript) | JavaScript | XQA Learn