Learn a valuable trick to activate CSS animation using a button - simply click on the button and watch the animation start over each time

I already know how to do this once. However, I would like the animation to restart or begin again when the user clicks on it a second time.

Here is what I have:

function animation() {
  document.getElementById('ExampleButton').className = 'Animation';
}
.ExampleButtonCSS {
  position: fixed;
  bottom: 113px;
  background: rgba(0, 0, 0, 0);
  color: #cfcfcf;
  width: 100%;
  padding-left: 20px;
}

#ExampleButton {
  cursor: pointer;
  font-size: 15px;
  outline-color: #000;
  outline-style: auto;
  outline-width: 2px;
  padding: 5px;
  border: none;
  background: rgba(0, 0, 0, 0.25);
  color: #cfcfcf;
  opacity: 0;
}

.Animation {
  opacity: 0;
  animation: inactivity 5s ease normal;
}

@keyframes inactivity {
  from {
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
<div class="ExampleButtonCSS">
  <button id="ExampleButton" onclick="animation()">Fade in and Out</button>
</div>

So, my question is, how can I make it so that when I click on it, the animation restarts if it's currently animating, or starts again if it has already completed at any point?

Answer №1

To achieve the desired effect, you must implement the animationend event.

<div class="ExampleButtonCSS">
  <button id="ExampleButton"> Fade in and Out </button>
</div>
const explmButton = document.getElementById('ExampleButton')

explmButton.onclick = () =>
  {
  explmButton.classList.add('Animation')
  }
explmButton.onanimationend = () =>
  {
  explmButton.classList.remove('Animation')
  }

Answer №2

I'm not quite sure what you're looking for.

One way to achieve the desired effect is by resetting the class of your element after the animation has finished.

function resetAnimation() {
  document.getElementById('ExampleButton').className = '';
  document.getElementById('ExampleButton').className = 'Animation';
  setTimeout(() => {
    document.getElementById('ExampleButton').className = '';
  }, 5000)
}
.ExampleButtonCSS {
  position: fixed;
  bottom: 113px;
  background: rgba(0, 0, 0, 0);
  color: #cfcfcf;
  width: 100%;
  padding-left: 20px;
}

#ExampleButton {
  cursor: pointer;
  font-size: 15px;
  outline-color: #000;
  outline-style: auto;
  outline-width: 2px;
  padding: 5px;
  border: none;
  background: rgba(0, 0, 0, 0.25);
  color: #cfcfcf;
}

.Animation {
  opacity: 0;
  animation: inactivity 5s ease normal;
}

@keyframes inactivity {
  from {
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
<div class="ExampleButtonCSS">
  <button id="ExampleButton" onclick="resetAnimation()">Fade in and Out</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

What is the process for creating a progress bar in PixiJS?

Can someone guide me on creating a progress bar similar to the one in PixiJS? Screenshot ...

Learn how to automatically retrieve messages without refreshing the page by leveraging the power of AJAX

displaying notifications with:- $call = "SELECT * FROM `chat` WHERE fromthe = '$email' and tothe='theadmin' UNION ALL SELECT * FROM `chat` WHERE fromthe = 'theadmin' and tothe='$email' order by id desc"; mysqli_quer ...

NextJS is currently unable to identify and interpret TypeScript files

I am looking to build my website using TypeScript instead of JavaScript. I followed the NextJS official guide for installing TS from scratch, but when I execute npm run dev, a 404 Error page greets me. Okay, below is my tsconfig.json: { "compilerOption ...

Convert TypeScript-specific statements into standard JavaScript code

For my nextjs frontend, I want to integrate authentication using a keycloak server. I came across this helpful example on how to implement it. The only issue is that the example is in typescript and I need to adapt it for my javascript application. Being u ...

How can you decode JSON using JavaScript?

Need help with parsing a JSON string using JavaScript. The response looks like this: var data = '{"success":true,"number":2}'; Is there a way to extract the values success and number from this? ...

CSS: How come this inline-block div is not appearing on the same line as intended?

I've been tinkering with using display:inline-block on my div elements, and I'm puzzled as to why my two inner divs aren't appearing on the same line. Both divs have a width of 200px, while their parent div is set at 400px. If I switch the ...

Retrieve the object when hovering over an element in the grid

In a collection of 16 items belonging to the same class, I am looking for a way to implement a mouseover effect that changes the opacity of only the specific item being hovered over and not all items in the class. Check out this link for an example ...

Achieving a seamless blend of parent background with child background: A step-by

I am trying to make the parent background color overlap the child background color in two divs. Currently, the child's background is overlapping the parent's background. Please refer to the JS-Fiddle link below for more information: <div id=" ...

Transmit information from Ajax to CodeIgniter's controller

Right now, I am facing an issue with sending data from my JavaScript to a function in the controller using AJAX. Despite my best efforts, AJAX is not sending the data. Below, you can find the code that I have been working on: The JavaScript Function var ...

What is the best method for storing a Google Analytics object in a $_SESSION variable when transitioning between PHP scripts to avoid encountering a non-object error

Currently in the process of developing a web application that integrates with the Google Analytics API, however encountering challenges when it comes to implementation. The user is given the option to choose their profile from three interconnected drop-do ...

Click the button to reset all selected options

<form method="post" action="asdasd" class="custom" id="search"> <select name="sel1" id="sel1"> <option value="all">all</option> <option value="val1">val1</option> <option value="val2" selected="selected"> ...

Utilizing the `filterBy` function with a custom select list that changes dynamically

I'm currently in the process of constructing a form with an extensive selection of drop-down items utilizing vue.js. My approach involves implementing the dynamic select list as detailed in this documentation: However, I am interested in providing us ...

When working with Node.JS, is it necessary to include 'event' if you include 'net' using the require statement?

As I examine the code, I notice that there is no instance of "require('event')" present. However, there is this piece of code: server.on('error', function (e) { if (e.code == 'EADDRINUSE') { console.log('Address in ...

What is the best way to transfer data from Material UI to Formik?

I'm facing an issue when trying to integrate a Material UI 'Select' component into my Formik form. It seems like I am unable to pass the selected values from the Material UI component to Formik's initialValues. const [selectedHours, se ...

What could be causing the Material UI tabs to malfunction when dynamically populating the content using a .map function instead of manually inserting it?

I was able to successfully integrate Material UI's tabs by manually adding content, but when I attempted to use a .map function to populate the content from a JSON data source, it stopped working. Can someone help me figure out why? The only change I ...

Creating a stacked chart in Angular using chart.js with JSON array of objects values

I am currently working on implementing a stacked chart using chart.js, and I have encountered some challenges: I am struggling to display currency values in the correct format on the chart (the height of the bar is not visible when passing amounts). How c ...

Upload file to database and move to new location

In order to gain a clearer understanding, I have a question regarding inserting data from a form. Let's say I have the following form: <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <inp ...

Why isn't the background of the container div at the top when using multiple CSS sheets?

I am revitalizing a dull website and seeking feedback on my template design here: Check out the ideal look It's quite lovely! However, as I attempt to incorporate my background, menu, and footer elements, I seem to be experiencing issues with my con ...

What is the method to obtain the coordinates based on a city name, and subsequently store those coordinates in a variable?

I'm currently exploring ways to extract the geographical coordinates based on user-provided city names. I am aware that Google offers this functionality through their API, but I am struggling with how to actually capture and store these results in PHP ...

The VueJS component failed to import successfully

Trying a simple demo to explore VueJS components, but encountering an error when loading the page: Unexpected Token Import in this line import GISView from './components/GISView.vue'; If I remove this line, GISView is not defined. Using Laravel ...