Is it possible to execute this animation with a single click for repetitive playback?

CODEPEN

const btt = document.querySelector('.btt');
  btt.addEventListener('click', function(){
  this.classList.toggle('anime');
});

Is there a way to achieve the desired effect with just one click?

Answer №1

I'm not sure if I comprehend your meaning.

If you want to replay the same animation with a single click, just add the following style to the mudaCor class:

animation-iteration-count: infinite;

Your CSS file should look like this:

*{
  margin:0;
  padding:0;
  box-sizing:border-box;
}

@keyframes mudaCor{
  0% {
    background: orange;
  }
  50% {
    background: blue;
  }
  100% {
    background: orange;
  }
  animation-iteration-count: infinite;
}

.btt{
  margin: 10px;
  padding: 10px;
  background: orange;
}

.mudaCor{
  animation: mudaCor 2s linear;
  animation-iteration-count: infinite;
}

I hope this information proves helpful to you.

Answer №2

To achieve this behavior, you can utilize the requestAnimationFrame method. Simply click the button to remove and then re-add the class in order to restart the animation.

var btt = document.querySelector('.btt');
btt.addEventListener('click', function() {
  this.classList.remove('mudaCor');
  requestAnimationFrame(() => {
    this.classList.add('mudaCor');
  });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

@keyframes mudaCor {
  0% {
    background: orange;
  }
  50% {
    background: blue;
  }
  100% {
    background: orange;
  }
}

.btt {
  margin: 10px;
  padding: 10px;
  background: orange;
}

.mudaCor {
  animation: mudaCor 2s linear;
}
<button class="btt">CLIQUE1</button>

Answer №3

Why not try utilizing setInterval to execute the click code repeatedly.

var button = document.querySelectorAll('.button')[0];
button.addEventListener('click', function() {
  let element = this;
  setInterval(function() {
    element.classList.toggle('changeColor')
  }, 1500)
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

@keyframes changeColor {
  0% {
    background: orange;
  }
  50% {
    background: blue;
  }
  100% {
    background: orange;
  }
}

.button {
  margin: 10px;
  padding: 10px;
  background: orange;
}

.changeColor {
  animation: changeColor 2s linear;
}
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=">
</head>

<body>
  <div class="container">
    <button class="button">CLICK</button>
  </div>
</body>

</html>

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

Problem with Express.js serving dynamically generated index.html page

Currently, I'm immersing myself in a practice project to grasp the concepts of express and webpack with react and react router. My goal is to make sure all server requests are directed to index.html to avoid encountering "Cannot GET" errors when navig ...

Getting latitude and longitude from Google Maps in a React Native appHere are the steps to

Looking to retrieve the latitude and longitude from Google using React Native. As a newcomer to React Native, I have been unable to find any resources to address this issue. Any assistance would be greatly appreciated. Thanks! Thanks ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

Steps to displaying the functions linked to a Jquery element

Currently diving into the realm of JQuery, I am on a quest to discover a method to access and view the associated methods of an object once it has been created, reminiscent of python's dir() function. ...

Is it possible to extract information from a form's POST request without relying on the traditional "action" attribute within form elements?

Last night, I was experimenting with ExpressJS and discovered something interesting when working with a simple code snippet: app.post('/contact', function(req, res, next) { res.send('Congratulations! You have submitted the form'); }) ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Implementing a custom button specifically for the month view in JavaScript FullCalendar

I have successfully added a custom button to my JavaScript full calendar code, but I would like this button to be displayed only in the month view. $(document).ready(function() { var calendar = $('#calendar').fullCalendar({ editable: tru ...

Send a basic variable from jQuery using Ajax to Ruby

I'm a beginner in the world of Ruby, jQ, and Ajax. I always make sure to do some reading before reaching out for help. My issue is with sending a basic jQuery variable to a Ruby controller using Ajax for a seamless transition. Is it possible to pass ...

Generate a Selectpicker dynamically when a button is clicked

Wanting to insert a new row in an HTML table dynamically by clicking on an add button. The new row includes a select element with the selectpicker class. Interestingly, when I remove the selectpicker class in my script to append a new row, the select eleme ...

Finding the correct closing tag in HTML can be accomplished using an algorithm

Currently working on my custom HTML parser in JAVA and have completed the lexer. Now diving into coding the parser to create a DOM tree and ensure the proper construction of my HTML. For example, understanding that an img tag is considered a void tag as p ...

Embedding videos in HTML

I am experiencing difficulties with embedding a video in my HTML file. I attempted to use a YouTube video, but when I open it in my browser, it displays an error message stating that the video is unavailable because YouTube has refused to connect. I also ...

What are the placeholders for the "localIdentName" query tag in a custom CSS-loader for Webpack?

Just starting out with Webpack and experimenting with the css-loader. I came across the option to specify a localIdentName query tag on the Github page under "Local Scope". This tag allows us to define our own custom values for how classes should be named ...

Steps to properly create your own angular service with XHR

Exploring the world of AngularJS, I embarked on a mission to create a file upload feature along with other form data. While there are numerous scripts and plugins available, I decided to utilize my own custom service using $xhr. Despite successfully sendin ...

Unable to fetch data in CakePHP 3.x controller using jQuery AJAX POST

I've been searching everywhere and unfortunately, I can't seem to figure out why the data is not being sent to my controller when posting via ajax. Here's the jQuery code snippet: var newDate = {}; newDate['start' ...

Spooky results displayed on website from NightmareJS

Is there a way to display the output from nightmareJS onto a webpage when a button is clicked using HTML, CSS, and JS? This is my nightmareJS code: var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: false}) nightmare .go ...

Any suggestions on how to incorporate the variable into the inline JavaScript [[]] API path?

I have a query regarding creating a URL in JavaScript, but I'm unsure how to include variables within th:inline="javascript". Below is my code snippet: <script th:inline="javascript"> $(function() { $('#querySubmit').click(queryS ...

What is causing `foo()` to function in this specific scenario?

Check out this code snippet: https://jsfiddle.net/5k10h27j/ I'm puzzled by why foo() is being called as an argument to a non-existent function. function foo(){ alert('huh??'); } jQuery('#container').on('change', ...

Deleting an element from an array in JavaScript

I am working with a JavaScript array that I need to store in local storage. var myArray; myArray = [1,2,3,4,5]; localStorage.setItem('myArray', JSON.stringify(myArray)); The above code snippet sets the values of the 'myArray' ...

Ways to retrieve information from the object received through an ajax request

When making an AJAX request: function fetchWebsiteData(wantedId) { alert(wantedId); $.ajax({ url: 'public/xml/xml_fetchwebsite.php', dataType: 'text', data: {"wantedid": wantedId}, typ ...