What could be the reason my spin animation is only triggered once upon button press?

Every time the submit button is clicked, I want all the images to spin. However, this rotation effect only works the first time the button is pressed, until the page is refreshed. I have used jQuery to add and remove a class from the images when the button is clicked, and the rotate animation is defined in my CSS.

I've streamlined my code to this point, but something seems off. Any help would be greatly appreciated!

function diceRoll() {
  $(".dice").removeClass("rotate");
  $(".dice").addClass("rotate");
}

document.getElementById("submit").addEventListener("click", function(e) {
  e.preventDefault();

  diceRoll();

})
/* Images */

img {
  width: 70px;
  line-height: 0;
  margin: 0 1%;
  display: flex;
  justify-content: center;
  display: inline;
}

figure {
  display: inline-block;
  vertical-align: middle;
}

.rotate {
  animation: rotation 0.1s infinite linear;
  animation-iteration-count: 2;
}

@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(359deg);
  }
}
<title>Diceey</title>

<!-- Bootstrap, CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="styles2.css">

<!-- Jquery Links -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>

<body>

  <div class="container-fluid heading">
    <h1 id="title"> Hello there</h1>
    <h5>Press to roll dice</h5>
  </div>

  <div class="container-fluid instructions">

    <!-- Images -->
    <div class="container-fluid">

      <div class="container-of-images">
        <figure>
          <img id="img1" class="dice" src="https://image.ibb.co/nFqkvx/dice6.png">
        </figure>

        <figure>
          <img id="img2" class="dice" src="https://image.ibb.co/nFqkvx/dice6.png">
        </figure>

        <figure class="threeChoices">
          <img id="img3" class="dice" src="https://image.ibb.co/nFqkvx/dice6.png">
        </figure>

        <figure class="fourChoices">
          <img id="img4" class="dice" src="https://image.ibb.co/nFqkvx/dice6.png">
        </figure>
      </div>
    </div>

    <div class="container-fluid">

      <div class="container-of-forms">
        <a href="" id="submit" class="btn btn-info btn-lg" role="button">Go</a>
      </div>
      <script src="index2.js" charset="utf-8">
      </script>
</body>

<footer>
</footer>

Answer №1

One approach could be to listen for the animation end event and then disable the "go" button while the dice is rotating.

function diceRoll() {
  $("a#submit").addClass("disabled")
  $(".dice").addClass("rotate");
  $(".dice").on("webkitAnimationEnd oanimationend msAnimationEnd animationend", function() {
    $("a#submit").removeClass("disabled")
    $(".dice").removeClass("rotate");
  })
}

function diceRoll() {
  $("#submit").addClass("disabled")
  $(".dice").addClass("rotate");
  $(".dice").on("webkitAnimationEnd oanimationend msAnimationEnd animationend", function() {
    $("#submit").removeClass("disabled")
    $(".dice").removeClass("rotate");
  })
}

document.getElementById("submit").addEventListener("click", function(e) {
  e.preventDefault();
  diceRoll();
})
img {
  width: 70px;
  line-height: 0;
  margin: 0 1%;
  display: flex;
  justify-content: center;
  display: inline;
}

figure {
  display: inline-block;
  vertical-align: middle;
}

.rotate {
  animation: rotation 0.1s infinite linear;
  animation-iteration-count: 2;
}

@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(359deg);
  }
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Diceey</title>

  <!-- Bootstrap, CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <link rel="stylesheet" href="styles2.css">

  <!-- Jquery Links -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>

<body>

  <div class="container-fluid heading">
    <h1 id="title"> Hello there</h1>
    <h5>Press to roll dice</h5>
  </div>

  <div class="container-fluid instructions">

    <!-- Images -->
    <div class="container-fluid">

      <div class="container-of-images">
        <figure>
          <img id="img1" class="dice" src="https://miro.medium.com/max/512/1*15_KIo9vPHULoA98NYT9jQ.png">
        </figure>

        <figure>
          <img id="img2" class="dice" src="https://miro.medium.com/max/512/1*15_KIo9vPHULoA98NYT9jQ.png">
        </figure>

        <figure class="threeChoices">
          <img id="img3" class="dice" src="https://miro.medium.com/max/512/1*15_KIo9vPHULoA98NYT9jQ.png">
        </figure>

        <figure class="fourChoices">
          <img id="img4" class="dice" src="https://miro.medium.com/max/512/1*15_KIo9vPHULoA98NYT9jQ.png">
        </figure>
      </div>
    </div>

    <div class="container-fluid">

      <div class="container-of-forms">
        <a href="" id="submit" class="btn btn-info btn-lg" role="button">Go</a>
      </div>
      <script src="index2.js" charset="utf-8">
      </script>
</body>

<footer>
</footer>



</html>

Answer №2

Utilizing the timeless power of CSS is my proposed solution for this task!

To implement these adjustments, simply modify your:

CSS file

img {
  width: 70px;
  line-height: 0;
   margin: 0 1%;
   display: flex;
   justify-content: center;
   display: inline;
}
 

figure {
  display: inline-block;
  vertical-align: middle;
}

.rotate {
  animation: rotation 0.1s infinite;
}

@keyframes rotation {
  0% {
    transform: rotate(0deg);
  }
  50%{
    transform: rotate(360deg)
  }
  100% {
    transform: rotate(0deg);
  }
}

JavaScript file

let a = document.querySelectorAll('.dice')
function diceRoll() {
  a.forEach(elem => {
    elem.classList.add("rotate");
    setTimeout(()=>{
      elem.classList.remove("rotate")
    }, 200)
  })

}

document.getElementById("submit").addEventListener("click", function(e) {
  e.preventDefault();
  diceRoll();

})

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

Managing sessions with jQuery

I have been attempting to store a value in a session object using jQuery, but I keep encountering an error that states "$.session function is not a function." I tried including the plugin "jquery.session.js" from GitHub, but it does not seem to work. Can ...

Concealing the initial table upon the arrival of the second table

I am attempting to display detailed rows when a user clicks on a cell in table R. The desired behavior is for Table L to appear and Table R to be hidden upon the second click. I initially tried using $('#RegionTable').hide, but it caused the tabl ...

Creating a visually appealing layout with Bootstrap 4's responsive card columns featuring cards of equal

My Django template has a structure similar to the following: <div class="container-fluid" style="padding: 25px"> <div class="card-columns"> {% for service in services %} <div class="card" ...

An AJAX request will only occur if there is an alert triggered on a particular computer

Here's an interesting issue I encountered with my company's CMS newsletter system. It seems that the AJAX call to send an email works flawlessly in all modern browsers and operating systems, except for one client. This particular client is using ...

It is essential for Jquery to properly evaluate the first JSON result, as skipping

I'm currently facing an issue where the first JSON result is being skipped when I try to evaluate a set of JSON results. Below is the Jquery code snippet in question: function check_product_cash_discount(total_id){ //check for cash discount ...

Ways to extract text from a temporary element

Here is my HTML code: <div class="p-login-info" ng-show="loggedOut()">My text.</div> This is the corresponding JavaScript code: var e = element(by.className('p-login-info')); e.getText() .then(function(text){ var logoutText = ...

What is the best way to extract text from a class using selenium?

<div class="class-one"> <div class="class-two"> lorem ipsum <div class="class-three"> <a href="https://yahoo.com" target="" class="btn btn--primary btn--purple " id="" title="find"><i class="fal fa-fw fa-file-word"></i>& ...

Looking for a jQuery plugin that creates a sticky top menu bar?

I am in search of a jQuery plugin (or code/guide) that can achieve this effect: Unfortunately, this particular one is not available for free Please take note that the navigation bar does not initially appear at the top but sticks once the viewport reache ...

What is the best way to modify tabulator styles?

Is there a way to update the column header in Tabulator using inline style when trying to avoid ellipsis as the column size is reduced? <VueTabulator ref="tabulator" v-model="receipts" :options="options" style="white ...

Guide on incorporating geolib into React Native for distance calculation of two locations

Is there a simple way to calculate the distance between Longitude and Latitude in react native? I have the coordinates of my current location and destination, but keep encountering errors when attempting to use geolib for this calculation. I attempted to ...

AngularJS ng-repeat is not updating when the state changes

Seeking assistance with an Angular application challenge I'm facing. I have implemented a ng-repeat in my app to display the latest messages stored in an array within a controller named "comunicacion": ng-repeat in comunicacion.html <div class=" ...

Triggering the onChangeMonthYear() event manually for jQuery datepicker

Currently, I am working with this function: $('#picker').datepicker({ // ... onSelect: function(currDate){ } }); I would like to manually trigger the onSelect() function, but using $('#picker').datepicker.onSelect(); does ...

Encountering excessive re-renders while using MUI and styled components

Hey there! I recently worked on a project where I used MUI (Material-UI) and styled-components to render a webpage. To ensure responsiveness, I made use of the useTheme and useMediaQuery hooks in my web application. My goal was to adjust the font size for ...

Adjust the background color and transparency of a specific section using HTML

Is there a way to modify the background color or opacity of a specific area within an image? Take a look at my HTML, JavaScript, and CSS: function changeColor() { document.getElementById('testid').setAttribute("class", "style1"); } ...

Is it possible to apply two ngClass directives to a single div element in Angular 4?

When I click to start editing, a component is called for the editing process. In this component, I am unable to click on anything and the background turns black, which is okay. However, I would like for each ID that I select to edit to become active with a ...

What are some strategies for transferring data using ajax?

I am trying to pass o_id as data, but I keep getting an error message: ReferenceError: invalid assignment left-hand side <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script type="text/javascript"> $("#ass ...

Delay the closure of a window by utilizing a straightforward method when selecting the "X - CLOSE" option with the following code: `<a href="javascript:window.open('', '_self').close();">X - CLOSE</a>`

I need to implement a delay when users click on the link to close a window. The purpose of this delay is to allow time for playing random "signoff" audio files, such as "Thanks!" or "See you next time!". Currently, without the delay, the audio stops abrupt ...

What causes the string to be treated as an object in React Native?

I am fetching a string value through an API and I need to display it in the View. However, the string value is coming as a Promise. How can I handle this? "Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65 ...

Stopping HTML 5 video playback while transitioning to a different webpage

My website has a layout with a left menu containing video links and a content area where the videos are played. However, I have encountered an issue when switching between videos. Currently, if I click on Video 1 and then decide to watch Video 2 while Vid ...

Creating a New Form Dynamically and Using Ajax to Submit it

I am currently working on creating a form object in my code and populating it with data from input elements on the page. Instead of submitting an existing form via ajax, I want this submit action to extract information from 4 specific fields within the for ...