Is there a way to detect the presence of a @keyframes rule without having to loop through all the

Looking for a method to determine if a CSS3 animation with a specific name is present, without the need to loop through all CSS rules. Any solution using either a JS library or plain JS will suffice.

Answer №1

One possible solution is to:

  1. Generate a dummy element.
  2. Attach an animationstart event to this dummy element.
  3. Assign the .style.animationName (with appropriate vendor-prefix).
  4. Place the element in the document and monitor if the event fires within a few milliseconds.

If the event does not trigger, it can be assumed that the animation does not exist. Remember to clean up by removing the element from the DOM.

This method operates asynchronously by design. It proves to be more dependable than scanning through all style sheets as the latter approach fails when an animation is specified in a style sheet from a different source.

Illustration

function checkIfAnimationExists(animationName, callback) {
    var dummy = document.createElement('dummy');
    var done = function(result) {
        if (dummy.parentNode) {
            dummy.parentNode.removeChild(dummy);
            callback(result);
        }
    };
    var onanimstart = function() {
        done(true);
    };
    // Animations only fire when the tab is visible:
    var requestAnimationFrame = window.requestAnimationFrame ||
                                window.mozRequestAnimationFrame ||
                                window.webkitRequestAnimationFrame;
    requestAnimationFrame(function() {
        done(false);
    });
    if (typeof dummy.style.animationName != 'undefined') {
        dummy.style.animationName = animationName;
        dummy.style.animationDuration = '0.001s';
        dummy.addEventListener('animationstart', onanimstart);
    } else {
        dummy.style.webkitAnimationName = animationName;
        dummy.style.webkitAnimationDuration = '0.001s';
        dummy.addEventListener('webkitAnimationStart', onanimstart);
    }
    (document.body || document.documentElement).appendChild(dummy);
}

The aforementioned function accurately detects whether an animation exists in browsers such as:

  • Firefox 16+ (for compatibility with FF 5 - 15, include a moz-prefixed branch).
  • Chrome 10+
  • Opera 12.1+
  • Safari 6.0 (for support prior to Safari 4 - 5.1, incorporate a polyfill for requestAnimationFrame)
  • Internet Explorer 10+

Live demonstration: http://jsfiddle.net/7mjSd/ (displays two alert boxes).

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

Issue with making requests across origins in Vuejs using axios

Currently, I am utilizing Vuejs and axios for handling web requests. So far, I have successfully managed to perform GET, POST, and PUT operations. However, the new challenge that I am facing is uploading media to the server. The server necessitates sending ...

Unable to assign a value to a dropdown using Angular.js and PHP

I am encountering a slight issue with setting the data as a selected value in a dropdown after fetching it from the database. Below is an explanation of my code. plan.html: <div class="input-group bmargindiv1 col-md-12"> <span class="input-g ...

'view' is not recognized as a valid property of the 'div' element in Ionic3, so it cannot be bound

I am a beginner with Ionic and I'm trying to incorporate Angular Calendar into my Ionic3 application. However, I am encountering an error that says, "Can't bind to 'view' since it isn't a known property of 'div'. Here&ap ...

CSS / SCSS: altering child element styles when parent is focused

Is there a way to change the style of child elements when focusing on a parent element without using javascript? For example, let's say we have: <li class="parent"> <div class="child1"></div> <div class="child2"></d ...

"Contrasting the initialization of state in the constructor with managing state

Can you explain the distinction between these two methods of initializing state in ES6 other than their access to props? constructor(props) { super(props); this.state = { highlighted: 5, backgroundColor: '#f3f3f3', ...

Additional spacing within nested divs utilizing the display: table property

In my current project, I am working on styling a list to resemble a table layout for horizontal alignment. The first column contains labels, while the second column features groups of buttons using Bootstrap's btn-group-justified class. This setup ess ...

The hydration error in next js is causing this code to malfunction

Why am I encountering a hydration error with this code in NextJS? The Items variable is an array of ReactNode's. Any suggestions for an alternative approach? I've searched extensively for information but haven't found anything related to Nex ...

Guidelines for placing an HTML element in relation to another HTML element using CSS or JavaScript

Is there a way to position an HTML element in relation to another using CSS or JavaScript? I have attempted to copy the inner HTML of the "second-element" and append it inside the "first-element", but this approach is causing issues with other functional ...

Utilize the onClick Event to Trigger Function with an Array in ReactJS

Every time I attempt to pass an array as a value to a function by clicking on a div, I encounter the error below: Uncaught Invariant Violation: Expected onClick listener to be a function, instead got a value of object type. If passing an array to a fun ...

`Finding it difficult to halt the spread of events in reactJs`

One of my conditions involves a simple dropdown menu: handleDropdown = (e) => { if (e.type === "focus") { console.log("inside dropdown focus"); this.setState({ dropDownDis: "block" }) } else if (e.type === "blur") { console.lo ...

Break up the content in table cells with a new line character

How can I get a string containing a new line character to wrap in a table cell? When I attempt to bind it, the text does not break at the new line character as expected. I have attached a screenshot for reference. In the console window, it displays correct ...

Utilize HTML, AJAX, and JavaScript to retrieve the location of the current user and display markers for other users on a

I am attempting to display on a single map the current location of a user and markers for other users, whose locations are obtained through an ajax post. In essence, I am looking to merge the concepts from: Google Maps Geolocation Example with: Multiple ...

Passing the Authorization Header for DataSource in GrapeCity's ActiveReportsJSLearn how to pass the

Our UI developer is working with VueJS, and we specifically need guidance on integrating JWT authentication within the ActiveReportsJS report viewer or designer. This is crucial as it's all based on JavaScript. We are currently utilizing JWT's w ...

"Is there a mysterious username lurking in the depths of cloud functions

I have a requirement to send a notification to a specific device, so I wrote this function and it seems to be working correctly. However, I am encountering an issue where the username is returning as undefined. Here are the logs output: Obtained data: a ...

Sending a File Object and Data to an MVC 6 Controller in ASP.NET 5 using JavaScript

I have been working with an Ajax function that is supposed to handle file upload, but I am encountering some issues. Despite dragging and dropping the file, nothing seems to happen with the Ajax. Upon inspecting the properties on the page, I can see that t ...

The download attribute in HTML5 seems to be malfunctioning when used within a React environment

I am experiencing an issue where the download button is not working as intended. Instead of downloading the images, it is redirecting to another page. I have tested this on multiple browsers, including Chrome, Edge, and my mobile device, but the problem pe ...

How to capture a change event in a dynamically loaded element using JQuery

I am facing an issue with dynamically added rows in my table. Each row contains a select option, and I need to trigger an action when the select is changed. However, since the rows are loaded after the page load, my function does not work as expected. < ...

Encountering a problem involving the apostrophe character "'" when trying to save content into a MySQL database

I have been developing an application that allows users to create HTML templates and save them. Users can utilize different components such as text, images, etc. to build HTML pages. Challenge: The issue I'm encountering is when a user inputs text wi ...

Express JS: Issue with chain promises halting at return statement in JavaScript

In my express app, I have a utility function that controls the promise then chain based on a specific condition. However, when I attempt to end the chain using a return statement, Express throws an error stating that headers cannot be set after they are se ...

Obtaining information from a local JSON file in AngularJS

I'm facing some issues with retrieving data from a JSON file using the structure below. In my controller.js file, I've written: var controllers = angular.module('hotels.controllers', []); controllers.controller('AppCtrl', f ...