Sling Academy
Home/JavaScript/Chain Multiple Animations Easily via the Web Animations API in JavaScript

Chain Multiple Animations Easily via the Web Animations API in JavaScript

Last updated: December 13, 2024

The Web Animations API is a powerful JavaScript tool that provides you with the ability to create, control, and synchronize intricate animations directly through your web page's scripts. It enables developers to combine multiple CSS animations seamlessly, offering more flexibility than traditional CSS animations. This article guides you through the basics of chaining multiple animations using the Web Animations API, ensuring your projects are both efficient and visually engaging.

Understanding the Web Animations API

The Web Animations API allows you to construct animations that interact with DOM elements. It works by letting you specify the keyframes and the animation properties directly in JavaScript. This eliminates the need for individual CSS animations, setting up a platform to build complex animation sequences easily.

Basic Structure of an Animation

To use the Web Animations API, you need to know about two main components:

  • Keyframes: These define the styles at various points in the animation sequence.
  • Timing Options: These specify the time-related properties of your animation such as duration, easing, delay, etc.

You can then use these two components to create animations which can be applied to DOM elements.

Chaining Animations

To chain animations, you sequentially execute different animations on the same or different elements. By doing so, you ensure a smooth visual flow from one animation to another. Chaining can be effectively utilized to enrich visual storytelling and create seamless UX transitions.

Creating a Simple Chained Animation

Let's delve into creating a basic chained animation using the Web Animations API. Assume we have a square element that we want to rotate and then increase in size.

<div id="square" style="width:100px;height:100px;background-color:blue;></div>

We'll first write a JavaScript code to rotate the square and then, once the rotation is finished, scale it up.

const square = document.getElementById('square');

// Define the keyframes for rotation
const rotateAnimation = square.animate([
  { transform: 'rotate(0deg)' },
  { transform: 'rotate(360deg)' }
], {
  duration: 1000, // 1 second
  iterations: 1,
  fill: 'forwards'
});

// Define the keyframes for scaling up
const scaleUpAnimation = square.animate([
  { transform: 'scale(1)' },
  { transform: 'scale(2)' }
], {
  duration: 1000,
  iterations: 1,
  fill: 'forwards'
});

// Chain the animations by performing the second animation after the first one ends
rotateAnimation.onfinish = () => {
  scaleUpAnimation.play();
};

In this example, once the rotation is complete, the scale up animation begins, creating a fluid transition between the two animations.

Advanced Chaining Techniques

With the capability to chain animations easily, you can expand to more complex sequences. Consider introducing a variety of animations for user-interactive scenarios, app loading indicators, or scrolling patterns.

Using Promises to Handle Animation Sequences

To manage more sophisticated animation flows, you can incorporate promises into your code to ensure your animations run synchronously, neatly handling chaining:

function animateElement(element, keyframes, options) {
  return new Promise((resolve) => {
    const animation = element.animate(keyframes, options);
    animation.onfinish = resolve; // Resolve the promise when animation finishes
  });
}

animateElement(square, 
  [{ transform: 'rotate(0deg)' }, { transform: 'rotate(360deg)' }],
  { duration: 1000, fill: 'forwards' }
).then(() => animateElement(square, 
  [{ transform: 'scale(1)' }, { transform: 'scale(2)' }],
  { duration: 1000, fill: 'forwards' }
));

This use of promises allows your animations to proceed in an orderly manner and makes it easy to insert further animations into the sequence.

Conclusion

The Web Animations API offers flexible possibilities for creating nuanced animation sequences that enhance the user experience. By understanding how to chain animations effectively and handle them with promises, you can easily manage complex animation workflows in an efficient and organized way. As you build more complex sequences, configuration and organization become vital, and the Web Animations API can help you maintain neat and understandable animations through your JavaScript.

Next Article: Enhance Visual Feedback Using the Web Animations API in JavaScript

Previous Article: Control Keyframes and Timing with the Web Animations API in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration