Home > Web Front-end > CSS Tutorial > How Can I Pause and Resume CSS3 Animations Using Only JavaScript?

How Can I Pause and Resume CSS3 Animations Using Only JavaScript?

Linda Hamilton
Release: 2024-12-07 10:43:11
Original
695 people have browsed it

How Can I Pause and Resume CSS3 Animations Using Only JavaScript?

Pause and Resume CSS3 Animation with JavaScript

Problem:

How to pause and resume a CSS3 animation using JavaScript without relying on external libraries?

Solution:

  1. CSS Animation:

Define the animation using CSS keyframes, specifying the opacity values and timing for each step.

  1. Pause and Resume Functions:

Create JavaScript functions to handle pausing and resuming the animation:

const pauseAnimation = (element) => {
  element.style.animationPlayState = "paused";
};

const resumeAnimation = (element) => {
  element.style.animationPlayState = "running";
};
Copy after login
  1. Event Listeners:

Add event listeners to the animated elements to trigger the pause and resume actions:

document.getElementById("pic1").addEventListener("click", () => {
  pauseAnimation(document.getElementById("pic1"));
});

document.getElementById("pic2").addEventListener("click", () => {
  resumeAnimation(document.getElementById("pic2"));
});
Copy after login

Additional Notes:

  • To ensure the animation can be paused multiple times, clear the existing event listeners before adding new ones.
  • Alternatively, use the CSS class approach proposed in the provided answer:
.paused{
    -webkit-animation-play-state:paused;
    -moz-animation-play-state:paused;
    -o-animation-play-state:paused; 
    animation-play-state:paused;
}
Copy after login
const pauseAnimation = (element) => {
  element.classList.add("paused");
};

const resumeAnimation = (element) => {
  element.classList.remove("paused");
};
Copy after login

This allows you to pause and resume the animation by simply toggling this CSS class without the need for event listeners.

The above is the detailed content of How Can I Pause and Resume CSS3 Animations Using Only JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template