When the CSS animation has finished in JavaScript

I am currently developing a game using HTML/JavaScript, and I have implemented a "special ability" that can only be activated once every x seconds. To indicate when this ability is available for use, I have created a graphical user interface element. Since I am incorporating CSS animations in my project, I need to determine whether the animation on this element has completed upon a keypress event.

Instead of utilizing addEventListener, I aim to achieve this functionality through a straightforward if statement. However, I am uncertain about the feasibility of this approach.

The code snippet I have so far is:

    var keystate = {};

    window.addEventListener("keydown", function(e) {
      keystate[e.keycode || e.which] = true;
    }, true);
    window.addEventListener("keyup", function(e) {
      keystate[e.keycode || e.which] = false;
    }, true);

    window.setInterval(function() {
      if (keystate[87]) { //w key, THIS is where I want to check if the animation has completed as well
        //do stuff
        document.getElementById("circle_flash_glow").classList.add("circle_flash_use");
      }
    }, 16.666666666666667);
#svg_circle_loader {
  position: absolute;
  right: 0;
  bottom: 0;
  background: none;
  border: none;
  margin: none;
  padding: none;
}
#circle_flash_loader {
  fill: none;
  stroke: #F00;
  stroke-width: 10px;
  stroke-dashoffset: 80;
  animation-fill-mode: forwards;
}
.circle_loader_load {
  animation: circle_flash_loading linear;
  animation-duration: 2.5s;
}
@keyframes circle_flash_loading {
  0% {
    stroke-dasharray: 0, 314;
  }
  100% {
    stroke-dasharray: 314, 0;
  }
}
#circle_flash_glow {
  fill: none;
  stroke: #F00;
  stroke-width: 0px;
  animation-fill-mode: forwards;
  opacity: 1;
}
.circle_flash_use {
  animation: circle_flash_pulse 0.6s ease-out;
}
@keyframes circle_flash_pulse {
  0% {
    opacity: 1;
    stroke-width: 0px;
  }
  100% {
    opacity: 0;
    stroke-width: 70px;
  }
}
<svg id="svg_circle_loader" width="200" height="200">
  <defs>
    <filter id="f1" x="-50" y="-50" width="200" height="200">
      <feGaussianBlur stdDeviation="5"></feGaussianBlur>
    </filter>
  </defs>
  <circle cx="100" cy="100" r="50" id="circle_flash_glow" class="" filter="url(#f1)"></circle>
  <circle cx="100" cy="100" r="50" id="circle_flash_loader" class="circle_loader_load"></circle>
</svg>

Answer №1

To add a variable to track the current state, and update it using setTimeout() to check if it is animating or not. Also, include window.onload to retrieve its state.

window.onload=function(){
  animating=true;
  sts.value=animating;
  window.setTimeout(function() {
    animating=false;
    sts.value=animating;
  }, 2500);
};

The value of 2500 is used based on your CSS animation property which is set to 2.5s=2500ms

var animating = false;
var keystate = {};

window.addEventListener("keydown", function(e) {
  keystate[e.keycode || e.which] = true;
}, true);
window.addEventListener("keyup", function(e) {
  keystate[e.keycode || e.which] = false;
}, true);

window.setInterval(function() {
  if (keystate[87]) { //w key, THIS is where I want to check if the animation has completed as well
    //do stuff
    if (!animating) {
      alert("animation finished");
      document.getElementById("circle_flash_glow").classList.add("circle_flash_use");
    }
  }
}, 16.666666666666667);

window.onload = function() {
  animating = true;
  sts.value = animating;
  window.setTimeout(function() {
    animating = false;
    sts.value = animating;
  }, 2500);
};
#svg_circle_loader {
  position: absolute;
  right: 0;
  bottom: 0;
  background: none;
  border: none;
  margin: none;
  padding: none;
}
#circle_flash_loader {
  fill: none;
  stroke: #F00;
  stroke-width: 10px;
  stroke-dashoffset: 80;
  animation-fill-mode: forwards;
}
.circle_loader_load {
  animation: circle_flash_loading linear;
  animation-duration: 2.5s;
}
@keyframes circle_flash_loading {
  0% {
    stroke-dasharray: 0, 314;
  }
  100% {
    stroke-dasharray: 314, 0;
  }
}
#circle_flash_glow {
  fill: none;
  stroke: #F00;
  stroke-width: 0px;
  animation-fill-mode: forwards;
  opacity: 1;
}
.circle_flash_use {
  animation: circle_flash_pulse 0.6s ease-out;
}
@keyframes circle_flash_pulse {
  0% {
    opacity: 1;
    stroke-width: 0px;
  }
  100% {
    opacity: 0;
    stroke-width: 70px;
  }
}
<svg id="svg_circle_loader" width="200" height="200">
  <defs>
    <filter id="f1" x="-50" y="-50" width="200" height="200">
      <feGaussianBlur stdDeviation="5"></feGaussianBlur>
    </filter>
  </defs>
  <circle cx="100" cy="100" r="50" id="circle_flash_glow" class="" filter="url(#f1)"></circle>
  <circle cx="100" cy="100" r="50" id="circle_flash_loader" class="circle_loader_load"></circle>
</svg>
<input id="sts" value="" />

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

I encountered an Angular error that is preventing me from updating and uploading images to my Firebase Storage because it is unable to locate the storage bucket

Hey there fellow developers! I'm currently working on a simple Angular app that allows users to upload images to a gallery. However, I've encountered an issue while trying to upload the images to Firebase Storage. I keep getting an error mentioni ...

I want the navigation bar to appear only upon scrolling, but when I refresh the page it is already visible, and then vanishes as I start scrolling

I'm working on a project where I want the navigation bar to only appear after scrolling a certain distance down the page. However, I've noticed that when I refresh the browser, the navigation bar appears immediately and then disappears once I sta ...

Exploring the Bounds of Mongodb's $within Query

I'm currently working on a geospatial query in mongodb using the $within operator. I have a collection entry with a location field containing: location: { bounds: { south_west: { lat: XX.XXXXXX, lng: XX.XXXXX }, north_east: { lat: XX.XXXXXX ...

Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appr ...

How to update a value within a deeply nested array in MongoDB and then sort the data

In my document, I have a list of timestamps that are sorted by time: { _id: '1', timestamps: [ { id: '589b32cf-28b3-4a25-8fd1-5e4f86682199', time: '2022-04-13T19:00:00.122Z' }, { id: '781 ...

What is the process of transferring information from one window to another window?

Is there a way to transfer data between two windows? In my parent window, I have a button that redirects to another page with a success button. When the success button is clicked on the child window, I want to display "success" text on the parent window. ...

Experience a seamless transition to the next section with just one scroll, allowing for a full

I've been attempting to create a smooth scroll effect to move to the next section using Javascript. However, I'm encountering issues with the window's top distance not being calculated correctly. I'm looking to have the full screen div ...

Looking for a way to prevent anonymous functions in jQuery using Greasemonkey?

Is there a way to prevent the execution of this particular jquery function? I've tried various scripts and even wrote my own, but nothing seems to work. $(document).ready(function () { $(window).on('beforeunload', function() { re ...

Assign a value to a locally scoped variable within an iteration in Angular 2

Within my Angular code, I have the following HTML snippet: <span *ngIf="ControllerType?.AttributeID =='Controller Type'"> <select multiple name="ControllerType.Default" [(ngModel)]="Contro ...

The page refreshes automatically when the search icon is clicked, but the ajax method does not trigger the page reload

Whenever I click on the search-box <a>, the JavaScript is triggered but doesn't execute the ajax method filter_data_guide_specs(). Instead, the page automatically reloads and fails to read the JS code. HTML <div class="form-group"> < ...

Why does my counter keep incrementing by more than one every time?

As I work on creating a test in jQuery, I've encountered an issue with my counter variable count. It seems to increase by more than one when the correct answer is used. function nextQuestion(){ $('#submit').show(); $('#next&apo ...

I'm a bit uncertain about the best placement for my progress bar component during the API call

Trying to grasp material ui I managed to implement the progress bar. Struggling with loading it until my data is fully loaded. Uncertain about where to place my progress bar component. Could you guide me on how to resolve this issue during API calls, so I ...

The art of positioning in menu - absolute versus relative

Struggling with positioning absolute divs is a common challenge for many of us. In my case, it's horizontal sub-menus with the following CSS: ul.children{ display:none; position:absolute; } ul.children li{ position:relative; height:60px; float:none; ...

Determine whether the child element extends beyond the boundaries of the parent element

I am currently working on determining whether a child element is visible within its parent element. To achieve this, I am comparing the width of the parent element to the position of the child element using position().left. Given that I have multiple dist ...

What is the proper way to define the scope for invoking the Google People API using JavaScript?

I am attempting to display a list of directory people from my Google account. export class People { private auth: Auth.OAuth2Client; private initialized: boolean = false; private accessToken: string; constructor(private readonly clientEmail: strin ...

Is it possible to easily remove the trailing comma, period, or other punctuation from the end when using the JavaScript pug template engine?

Apologies for the confusion in my question wording. To illustrate, here is an example piece of code: p #[strong Genre]&nbsp; each val in book.genre a(href = val.url) #{val.name} | , I am trying to figure out how to format a comma ...

Enhance your data retrieval from XPATH using Javascript

Here is the layout of an HTML template I am working with: <div class="item"> <span class="light">Date</span> <a class="link" href="">2018</a> (4pop) </div> <div class="item"> <span class="light">From</sp ...

Utilizing tables for inquiries in email communication

Currently tackling a basic mailer with html. It seems like tables are recommended and inline styling is the safer route. However, I'm encountering an issue where there's a mysterious space when setting up my td and I can't seem to pinpoint ...

When a website is deployed to an application, the process includes MVC bundling and managing relative CSS image paths

When trying to convert relative image paths to absolute paths, there are numerous queries on stackoverflow addressing this issue. For example, take a look at this thread: MVC4 StyleBundle not resolving images This question recommends using new CssRewrite ...

Creating valuable properties in TypeScript is a skill that requires knowledge and practice

In TypeScript, there is a unique feature available for defining properties with values using the `value` keyword. class Test { constructor(private value: number = 123) { } public MyValueProperty: number = 5; } Here is how you can define such ...