How can I trigger a CSS animation to replay each time a button is clicked, without relying on a timeout function?

I am having trouble getting a button to trigger an animation. Currently, the animation only plays once when the page is refreshed and doesn't repeat on subsequent clicks of the button.

function initiateAnimation(el){  document.getElementById("animationBox").style.animationPlayState = "running";
}   
#animationBox {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: spin; 
  animation-duration: 3s;  
  animation-delay: 1s;
  animation-play-state: paused;
}

@keyframes spin {
  0% {background-color: yellow;}
  50% {background: purple;}
  100%{background: red;}
}
<div id="animationBox"></div>;

<div><button onclick="initiateAnimation(this)" class="fas fa-play">&nbsp;&nbsp;Click Me!</button></div>

Answer №1

Within my example provided, I utilized the addEventListener function to detect the end of an animation and subsequently reset it.

const myTest = document.getElementById("myTest");
function initiateAnimation(el) {
  myTest.style.animationPlayState = "running";   
}
myTest.addEventListener("animationend", () =>{
  myTest.style.animation = 'none';
  myTest.offsetHeight;
  myTest.style.animation = null; 
}, false);
#myTest {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;
  animation-delay: 1s;
  animation-play-state: paused;
}

@keyframes example {
  0% {
    background-color: yellow;
  }
  50% {
    background: purple;
  }
  100% {
    background: red;
  }
}
<div id="myTest"></div>
<div>
  <button onclick="initiateAnimation(this)" class="fas fa-play">&nbsp;&nbsp;Click here</button>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tired of searching for a way to activate the Inspect function in the right-click menu on a custom dialog while debugging Google apps

I'm currently working on implementing a file picker function within Google Sheets by using the Google Picker API. Although I have managed to display a customized dialog window for selecting files from my Google Drive, the output is not exactly what I ...

Troubleshooting a Cache Issue in Your Next.js Application

Whenever I attempt to run 'npm run build', an error crops up that seems to be linked to the css and fonts. Unfortunately, I am unsure of how to tackle this problem. It's perplexing as the app functions perfectly fine in development mode. Th ...

Vuejs components that have checkboxes already selected out of the box

Hey there, I'm facing a small issue. Whenever I click on the areas highlighted in the image, the checkbox on the left gets marked as well. Any idea why this might be happening? https://i.stack.imgur.com/nqFip.png <div class="form-check my-5&qu ...

Implementing basic authentication in Socket.IO on a Node.js server

Currently, I am attempting to develop a basic websocket client for establishing a connection with a device. However, the device requires both a username and password for authentication purposes, posing a challenge for me as I struggle to figure out how to ...

Issue with Yeoman webapp generator and Gulp, encountering error when using Gulp-jade package

I'm encountering some difficulties integrating jade with yeoman's gulp webapp generator. The watch task is functioning properly, but when I attempt to build the project, I encounter the following error: stream.js:94 throw er; // Unhandled ...

Selecting options in an input field using AngularJS

In my AngularJS template, I have the code snippet below: <input type="number" id="exercise-log-duration-hours-{{ ::$id }}" class="form-control" ng-model="$ctrl.workoutHours" ng-change="$ctrl.updateHours($ctrl.workoutHours)" name ...

Adjust the width of the graphics on both sides of the text based on the length of the text content

Is there a way to center an H1 tag between two graphics using CSS or jquery/javascript? The width of the H1 text will vary depending on the page. The dot on the left should remain at the edge of the site, and the line should extend to meet the edge of the ...

The table appears to be fixed in place and will not scroll, even though the data

Previously, my code was functioning perfectly with the mCustomScrollbar I implemented to scroll both vertically and horizontally on my table. However, while revising my jQuery code for organization purposes, I seem to have unknowingly altered something tha ...

Using window.print as a direct jQuery callback is considered an illegal invocation

Curious about the behavior when using Chrome $(selector).click(window.print) results in an 'illegal invocation' error $(selector).click(function() { window.print(); }), on the other hand, works without any issues To see a demo, visit http://js ...

Encountering difficulty accessing the router during testing in Next.js

Hello, I'm currently attempting to test a scenario where when a button is pressed, it should redirect to '/'. Normally this works fine, but during testing it fails and shows the following error: Cannot read properties of null (reading ' ...

When scrubbing through videos, Chrome consistently throws a MEDIA_ERR_DECODE error

Encountering a MEDIA_ERR_DECODE error while scrubbing in Chrome on two different PCs. One PC runs Windows 7 with Chrome version 26, and the other runs Windows 8 with Chrome version 27. This issue occurs across all videos. When attempting to scrub on the v ...

Align two separate unordered lists together in the center

Would it be possible to align two separate UL elements next to each other horizontally? Here is the code that I am currently working with: <div id="container"> <ul id="list1"> <li></li> <li></li> ...

Looking for Sha1 encryption functionality in jQuery or JavaScript?

I am currently using sha1 encryption coding in PHP <?php echo hash('sha1', 'testing'.'abcdb'); ?> However, I need this encryption to work on a page named xyz.html, causing the current block of code to not function prop ...

"Troubleshooting: ngForm.controls returning undefined value in Angular application

Trying to test this HTML code in Angular: <form name="formCercarUsiari" #formCercarUsuari="ngForm" class="tab-content"> <input #inputNif class="form-control input-height" maxlength="100" type="text" placeholder="Indiqui NIF" name="nif" i18n-pla ...

When using the `.push` method, the array becomes null

Currently, I am in the process of developing an angular application. Within my component's .ts file, there exists an array structured as follows: public myArray = []; public dataFromAPI = []; In a particular method within this component, whenever I ...

The correct assertion of types is not carried out during the initialization of generics through a constructor

I am encountering a minor issue with TypeScript, and I am uncertain whether it is due to a typo on my part or if TypeScript is unable to correctly infer the types. Let me provide all the necessary code to replicate the problem: interface IRawFoo { type: s ...

Display numerous occurrences of a certain class by utilizing a different class

I'm currently in the process of creating a board game similar to Ludo, which requires a grid of 13x13 squares. I've created a Box class that successfully renders a single square button. Here's the code: class Box extends React.Component{ r ...

It is my goal to populate the array with numbers while avoiding any duplicate entries

I am currently facing an issue with my code as it is returning a length of 0 instead of the expected result of 5 after excluding duplicates from the array. I have a feeling that there might be something missing in my code, but I just can't seem to fig ...

Do I need to make any changes to the application when adding a new couchbase node to the cluster

Currently, I am utilizing the Node.js SDK to establish a connection with a couchbase cluster. Despite this, in the Node.js documentation, there is no clear instruction on how to input multiple IP addresses (of cluster nodes) when creating the cluster objec ...

Displaying an iframe in Internet Explorer

My current setup involves a button that triggers the loading and printing of a report within an "invisible" iframe enclosed in a div. This process allows users to print the report from a different page without any visual disruption or changing pages, aside ...