vadnica-logo
Editor My Blog My Services About the Project Telegram O meni O meni

JavaScript Animations

Modern web development requires visual dynamics in addition to static data output. With JavaScript animations, we can achieve smooth movement, resizing, fading, or reacting to user clicks. Although many animations can be done using CSS, JavaScript provides complete programmatic control – an animation can be triggered at a precise event, paused, reversed, or have its speed altered based on user input.

EXAMPLE
RESULT

The Modern Way: Web Animations API

The most modern and efficient way to animate elements in pure JavaScript is by using the element.animate() method. This method interfaces directly with the browser engine, delivering the same speed and smoothness as CSS transitions, but with all the advantages of JavaScript control.

The method accepts two key arguments:

  1. Array of Keyframes: A list of objects where each object represents a specific state of the element (from start to finish).
  2. Options Object: Settings such as duration in milliseconds, pacing (easing), and loop count.

Code Structure and Syntax

Let's look at a simple example of moving an element while simultaneously changing its opacity. This line of code is typically executed inside a function upon a click event:

element.animate([
    // Step 1: Initial state
    { opacity: 0, transform: "translateY(-20px)" },
    // Step 2: Final state
    { opacity: 1, transform: "translateY(0)" }
], {
    // Animation settings
    duration: 400, // Duration: 400 milliseconds
    easing: "ease-out" // Smooth deceleration at the end
});

When to Use CSS vs. JavaScript?

For successful development, it is important to know which tool to select for a given task:

Technology Best Suited For... Advantages
CSS Transitions / Keyframes Simple interactions, such as color transitions on mouse hover, straightforward buttons, and loading spinners. Exceptionally fast performance, less code, and the browser optimizes it automatically.
JavaScript (animate()) Complex animations, chaining effects (one animation starts right after another ends), moving elements based on mouse position, or dynamic simulators. Complete programmatic control (start, pause, reverse) and the ability to track animation completion via events (Promises).

Controlling Playback and Animation Events (Cheat Sheet)

When you trigger an animation in JavaScript using the animate() method, it returns an **Animation object**. Through this object, you can programmatically stop, pause, or catch the exact moment the animation successfully finishes.

Method / Property Type / Description Syntax / Use Case Example
1. Programmatic Playback Control (Methods)
play() Starts or resumes a paused animation. myAnimation.play();
pause() Pauses the animation at the current frame. myAnimation.pause();
finish() Immediately jumps to the very last frame of the animation and completes it. myAnimation.finish();
cancel() Cancels the animation and instantly clears all effects, resetting the element. myAnimation.cancel();
reverse() Reverses the playback direction, running it backward toward the start. myAnimation.reverse();
2. Listening for Events and States (Events & Promises)
playState A property that returns the current playback state (e.g., "running", "paused", "finished", "idle"). if (myAnimation.playState === 'paused') { ... }
onfinish An event that triggers the exact millisecond the animation naturally finishes. myAnimation.onfinish = function() { alert('Done!'); };
finished (Promise) A modern alternative allowing for asynchronous code chaining upon animation completion. myAnimation.finished.then(() => { ... });
oncancel An event that fires if the animation is forcefully cleared using the cancel() method. myAnimation.oncancel = function() { ... };

Connection to CSS Events: If you were using traditional CSS animations via classes instead of the Web Animations API, you would listen for these milestones in JavaScript using standard event listeners such as element.addEventListener('animationend', ...);, animationstart, or animationiteration (when the animation loops).