Is there a way to continuously switch a CSS animation class without needing a second click?

I am seeking a solution to animate the color and size of a div box, then return it to its original state when a button is clicked. Here is an example of my code:

document.getElementById("andAction").addEventListener("click", function() {
    document.getElementById("box").classList.toggle("animi");
})
.thing {
  transform: translate(150px, 100px);
}

.box {
  background-color: #999;
  padding: 2px;
  color: black;
  width:20px;
  margin: 0 auto;
  text-align: center;
  color: #fff;
}

@keyframes blob {
  0%  { 
         background-color: #999;
      }
  50% { 
        background-color: #F9086D;
        transform: scale(2);
        background-color: red;
        border-radius: 20px;
      }
  100% { 
        background-color: #999;          
      }
 }

.animi {
  animation-name: blob;
  animation-duration:3s;
  animation-iteration-count:1;
}
<button id="andAction" class="button">button</button>

<div id="box" class="box>1</div>

Issue

The problem I encountered was with using toggle, requiring two clicks for the desired effect. I also tried classList.add followed by remove, but this did not initiate the animation. Using timeout was one workaround.

Query

I believe there might be another approach to achieve this. Any suggestions?

Answer №1

If you want to get rid of the class after an animation ends, you can utilize the onanimationend event instead of using complex timers:

const boxElement = document.getElementById("box")

boxElement.addEventListener('animationend', (e) => {
  // Check if the target is the box itself and the animation name is 'blob', then remove the class
  if (e.target === boxElement && e.animationName === "blob") {
    boxElement.classList.remove('animi');
  }
})

document.getElementById("andAction").addEventListener("click", function() {
    boxElement.classList.add("animi");
})

Answer №2

To automatically remove the class after the animation finishes and change the initial behavior to only add the class, you can use JavaScript along with the animationend event.


const box=document.getElementById("box");

document.getElementById("andAction").addEventListener("click", function() {
  box.classList.add("animi");
});

box.addEventListener('animationend', () => {
  box.classList.remove("animi");
});
.thing {
  transform: translate(150px, 100px);
}

.box {
  background-color: #999;
  padding: 2px;
  color: black;
  width: 20px;
  margin: 0 auto;
  text-align: center;
  color: #fff;
}

@keyframes blob {
  0% {
    background-color: #999;
  }
  50% {
    background-color: #F9086D;
    transform: scale(2);
    background-color: red;
    border-radius: 20px;
  }
  100% {
    background-color: #999;
  }
}

.animi {
  animation-name: blob;
  animation-duration: 3s;
  animation-iteration-count: 1;
}
<button id="andAction" class="button">button</button>

<div id="box" class="box">1</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

The successful loading of tab favicons in the DOM of an angular chrome extension is a triumph, however, explicit XHR requests are unfortunately

I've been immersed in developing a Chrome extension with Angular 5. Successfully, I managed to extract favIconUrls from the tabs API and link them to my popup.html's DOM. The icons are retrieved and displayed without any hiccups. See an example ...

What might prevent an onSubmit event from triggering the execution of "checkTheForm()"?

Despite consuming a substantial amount of information on the internet, I still find myself puzzled by why my code isn't functioning as expected. I acknowledge that there are numerous tutorials out there guiding me to use <form action="index.html" o ...

Is it possible for me to use an NPX tool to execute git clone command?

I am currently working on developing a personalized NPX tool that will install my custom npm package onto a locally hosted server. At the moment, I have a layout template that I want other users to replicate when they run my NPX command. Here is an exampl ...

What could be causing the CSS transition to fail when the menu button is clicked?

After clicking on the menu, a class 'active' is added to both the 'div' and 'section' elements. https://i.stack.imgur.com/jbamR.png The following javascript code accomplishes the above functionality: <script> const ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Should I wait for my state to be updated with new information before triggering the render function?

Can someone assist me with restructuring the code below to ensure that the information in the data array is displayed on the initial page load? async componentDidMount() { const { id } = this.props.match.params const soccerApi = axio ...

The PurgeCSS CLI does not generate CSS files beyond the command line interface

I'm struggling to successfully extract my CSS using purgecss from the command line and save it to a separate file. The instructions on PurgeCSS.com are vague: By default, the CLI only outputs the result in the console. To save the purified CSS files ...

xhttp.load path for server-side module

I'm currently working on developing a node package and in my JavaScript code, I have the following: const calcHtml = './calc.html'; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { ...

Center the R Shiny showNotification on the screen

Currently, I'm exploring ways to customize the feature of showNotification() in Shiny. Link to example notifications My goal is to have the message appear at the center of the screen instead of the bottom-right corner. While it doesn't seem pos ...

Why Safari is Not Displaying Drop Shadows on SVG Path Elements in CSS

I implemented an SVG triangle using HTML: path { fill: red; filter: drop-shadow(5px 3px 17px rgb(0 0 0 / 1)); } <svg style="height: 36px; width: 100%; background-color: #EAEAEA ;" viewBox="0 0 436 217" preserveAspectRatio="none" class="Tagline ...

Capturing member function details using JSDoc

Here's the code snippet I'm working with: /** This class blah blah... @constructor **/ my.namespace.ClassA = function(type) { /** This function performs an action **/ this.doSomething = function(param){ } } The class will be inc ...

Which language is better for refreshing web pages: PHP or Javascript?

May I seek your opinion on this matter? I have the ability to refresh my page using two different methods, but I am uncertain of any potential drawbacks. Can you advise me on which one I should utilize? Edit: Specifically, I am referring to the use of he ...

Text arranged in a vertical orientation with a group of text aligned along the baseline

I am trying to create the following layout: https://i.sstatic.net/HYNDw.png Here is what I need: The word total and the number 120 should align vertically in the center The words per month should align at the bottom with respect to the number 120 The ...

In an Electron-React-Typescript-Webpack application, it is important to note that the target is not a DOM

Rendering seems to be working fine for the mainWindow. webpack.config.js : var renderer_config = { mode: isEnvProduction ? 'production' : 'development', entry: { app: './src/app/index.tsx', //app_A: './src/a ...

What is the best way to keep a <div> class anchored to the bottom of an HTML page?

I am looking to incorporate a footer into my website that stays fixed at the bottom of the screen. However, I have encountered an issue: Here is what I have attempted so far: .footer { position: absolute; width: 100%; background: #0084FF; ...

Show only the present y-coordinate in the ToolTip of a chart.js

I am currently working on developing a chart using Chart.js, and my goal is to only show the y-axis value in the tooltip. The current display shows: date name_of_line: measurement example: Jan 1, 2020, 8:00:00 AM 5th Percentile: 100 oz. However, I would ...

What could be causing Next.js to throw an error upon completion of the MSAL OAuth process?

I encountered an error while building a website using next.js. The site is set up for production, and after the authentication process with MSAL for Azure AD integration, I am facing the below error during the OAuth loop. As a beginner in next.js coming fr ...

"Upon updating, the array within the mapped state to props in React Redux appears to be

As I work on updating a user's profile through a form, my goal is to ensure the component rerenders after the update and displays the correct information on the form once saved. Here is what I have implemented so far: ProfileInput.tsx const ProfileI ...

The React component fails to inherit any props that are passed to it when it is rendered using a logical operator

I'm facing an issue with a component that doesn't seem to receive any props when I use a logical operator in conjunction with it. Oddly enough, if I render the component without the conditional statement, everything works fine. But as soon as I a ...

Transcluding content inside a table cell with Angular

Recently, I came across a peculiar issue with an attribute directive in Angular. This directive simply adds a class name to the element where it is applied, specifically to a table cell <td>. Oddly enough, when I set transclude: true in the directive ...