New Post Released!

🎉 Don’t miss out! Click here to subscribe and be the first to get our latest updates! 🚀

— · 4 Min read

How to Control CSS Animations with JavaScript

CSS animations are a powerful tool for adding dynamic effects to web pages. While CSS provides robust tools for animations, combining it with JavaScript offers even greater control, allowing you to interactively manage animations based on user actions or other conditions. In this article, we’ll explore how to use JavaScript to control and manipulate CSS animations.

1. Setting Up a Basic CSS Animation

Let's start with a basic example of a CSS animation. We will create a box that moves from left to right.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Basic CSS Animation</title>
  <style>
    .box {
      width: 100px;
      height: 100px;
      background-color: skyblue;
      position: relative;
    }
 
    .move {
      animation: moveRight 2s infinite;
    }
 
    @keyframes moveRight {
      0% { transform: translateX(0); }
      100% { transform: translateX(300px); }
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <button id="start">Start Animation</button>
  <button id="stop">Stop Animation</button>
  <button id="reverse">Reverse Animation</button>
  <script src="script.js"></script>
</body>
</html>

In this setup:

The .box class styles a square box. The .move class applies an animation that moves the box horizontally. The @keyframes rule defines the animation named moveRight, which moves the box from its initial position to 300 pixels to the right.

2. Controlling Animations with JavaScript

JavaScript can control CSS animations by adding or removing classes or manipulating CSS properties directly. Let's look at some common controls.

Starting and Stopping Animations You can use JavaScript to start and stop the animation by toggling the animation class.

// script.js
const box = document.querySelector('.box');
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
 
startButton.addEventListener('click', () => {
  box.classList.add('move');
});
 
stopButton.addEventListener('click', () => {
  box.classList.remove('move');
});
 

In this example:

Clicking the "Start Animation" button adds the move class to the box, initiating the animation. Clicking the "Stop Animation" button removes the move class, stopping the animation.

3. Reversing the Animation

To reverse the animation direction, you can toggle the animationDirection property.

// script.js
const reverseButton = document.getElementById('reverse');
 
reverseButton.addEventListener('click', () => {
  const currentDirection = box.style.animationDirection || 'normal';
  box.style.animationDirection = currentDirection === 'reverse' ? 'normal' : 'reverse';
});

This script:

Toggles between 'normal' and 'reverse' values for animationDirection, altering the animation’s direction.

3. Dynamic Animation Control

Sometimes you might want to dynamically adjust animation properties such as duration and delay.

// script.js
const durationInput = document.createElement('input');
const delayInput = document.createElement('input');
const applyButton = document.createElement('button');
 
durationInput.type = 'number';
durationInput.placeholder = 'Duration (s)';
delayInput.type = 'number';
delayInput.placeholder = 'Delay (s)';
applyButton.textContent = 'Apply';
 
document.body.appendChild(durationInput);
document.body.appendChild(delayInput);
document.body.appendChild(applyButton);
 
applyButton.addEventListener('click', () => {
  const duration = durationInput.value;
  const delay = delayInput.value;
  
  box.style.animationDuration = `${duration}s`;
  box.style.animationDelay = `${delay}s`;
});

In this example:

Creates input fields to specify the animation duration and delay. Updates the animation properties dynamically based on user input.

4. Pausing and Resuming Animations

Control the playback state of animations using the animationPlayState property.

// script.js
const pauseButton = document.createElement('button');
const resumeButton = document.createElement('button');
 
pauseButton.textContent = 'Pause Animation';
resumeButton.textContent = 'Resume Animation';
 
document.body.appendChild(pauseButton);
document.body.appendChild(resumeButton);
 
pauseButton.addEventListener('click', () => {
  box.style.animationPlayState = 'paused';
});
 
resumeButton.addEventListener('click', () => {
  box.style.animationPlayState = 'running';
});

Here:

The "Pause Animation" button sets animationPlayState to 'paused', freezing the animation. The "Resume Animation" button sets it back to 'running', continuing the animation from where it left off.

5. Creating Custom Animations with JavaScript

For more advanced control, you can create custom animations using JavaScript directly.

 
// script.js
function animateElement(element, start, end, duration) {
  const startTime = performance.now();
 
  function animate(time) {
    const elapsed = time - startTime;
    const progress = Math.min(elapsed / duration, 1);
 
    element.style.transform = `translateX(${start + (end - start) * progress}px)`;
 
    if (progress < 1) {
      requestAnimationFrame(animate);
    }
  }
 
  requestAnimationFrame(animate);
}
 
const animateButton = document.createElement('button');
animateButton.textContent = 'Custom Animation';
document.body.appendChild(animateButton);
 
animateButton.addEventListener('click', () => {
  animateElement(box, 0, 300, 2000);
});

This script:

Defines a animateElement function that animates an element from a start to an end position over a given duration. Adds a button to trigger this custom animation.

Conclusion

Combining CSS animations with JavaScript allows for dynamic and interactive web experiences. By using JavaScript to start, stop, reverse, and dynamically control animations, you can create more engaging and user-responsive interfaces. Experiment with these techniques to enhance your web projects!