Unable to apply insertRule with keyframes

When using CSS without keyframes, insertRule functions perfectly. However, if a CSS with keyframes is used, an error occurs:

Failed to execute 'insertRule' on 'CSSStyleSheet': Failed to parse the rule ...

The following code works:

const css = window.document.styleSheets[0];
css.insertRule(`
div {
  width: 100%;  
  animation: move 2s;
  position: absolute;
  transition: 0.65s;
}
`, css.cssRules.length);

This code does not work:

const css = window.document.styleSheets[0];
css.insertRule(`
div {
  width: 100%;  
  animation: move 2s;
  position: absolute;
  transition: 0.65s;
}
@keyframes move {
  0% {
    left: 0;
  }
  20% {
    left: 100px;
  }
  100% {
    left: -100%;
  }
}
`, css.cssRules.length);

Any suggestions on how to make it work?

Answer №1

The code posted attempts to add two rules using just one call to the insertRule method.

By making two separate calls, you can successfully insert each rule individually:

const css = window.document.styleSheets[0];
css.insertRule(`
div {
  width: 100%;  
  animation: move 2s;
  position: absolute;
  transition: 0.65s;
}
`, css.cssRules.length);
css.insertRule(`
@keyframes move {
  0% {
    left: 0;
  }
  20% {
    left: 100px;
  }
  100% {
    left: -100%;
  }
}
`, css.cssRules.length);
div { height: 3em;}
<div> DIV element</div>

This approach will execute without any errors. The MDN documentation provides information on the restrictions of the insertRule method when it comes to multiple rules in the parameter, which can result in a syntax error. More details can be found in the listed Restrictions.

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 best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class. interface IQuiz { quizProg: TypeQuizProg; qidx: number; state: IStateCtx; actions: IActionsCtx; } @observer class Comp extends Rea ...

Interactive map with AngularJS featuring dynamic markers and real-time updating of marker position

In my Angular application, I have integrated a Google Map with a marker. I am looking to make the marker move along with the map as it is being moved. Currently, the marker stays in its default position when the map is moved. How can I achieve the effect ...

Implementing date range filtering in AngularJS model using filters

Within my view, I have the following: <tr dir-paginate="post in posts |orderBy:propertyName:reverse | filter: searchPost | itemsPerPage: pageSize"> <td> {{post.title}} </td> <td> {{post.content}} </td> <td& ...

AngularJS service using $http.get is failing to transfer data to a controller

Just getting started with AngularJS and I'm running into some challenges with the basics. I've been working on a service that uses $http.get to load a couple of Json files. However, when I try to use the service in my controller, I end up with e ...

Is there a way to generate random numbers that will create a chart with a general upward trend?

Are you looking for a solution to generate random numbers for charts that trend upwards and to the right? I am currently utilizing a JavaScript charting engine, so I will require numbers in JSON format eventually. However, I am open to alternative methods ...

Guide to importing external CSS styles into Angular 2 using the require method

I'm facing an issue with loading an external css file in different environment files. My setup includes two environments: development and production. Loading the css file locally works fine in development mode, but not in production mode. environment ...

React and Material-Ui utilize class definitions in .js files, which are then passed as strings to components

I am attempting to define a class within my .js file in order to utilize the material-ui theme object and pass it as a string to a component since the component's prop only accepts strings. Unfortunately, the React-Dropzone import does not accept a cl ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...

Using Zombie.js to simulate clicking on a Javascript link

I am currently using Node.js in combination with Zombie.js for web scraping. There are certain pages on which I need to interact with JavaScript links. For instance, consider the following page: http://www.indotrading.com/company/berkat-jaya-electronics. ...

The local() function in CSS @font-face is limited to finding only the "regular" and "bold" font styles, not others

Recently, I added some new fonts (specifically Roboto) to my Linux Ubuntu PC and wanted to incorporate them into my CSS using the @font-face rule. However, I encountered an issue when specifying different font weights within the src: ; property as shown in ...

Leveraging Multiple MongoDB Databases in Meteor.js

Can 2 Meteor.Collections fetch data from separate MongoDB database servers? Dogs = Meteor.Collection('dogs') // mongodb://192.168.1.123:27017/dogs Cats = Meteor.Collection('cats') // mongodb://192.168.1.124:27017/cats ...

Passing PHP data from one div to another using JQuery: A step-by-step guide

My HTML code looks like this: <div class="right"> <h2>Product Detail</h2> <div id="righttop"></div> <button id="Add">Add</button> </div> <div class="rightbot"> <h2>Shopp ...

Comparing Two Arrays in AngularJS and Disabling on Identical Cases

I currently have two tables: "Available subject" and "Added subject" which are populated by ng-repeat with two separate lists of objects. My objective is to accomplish three things: 1 - When the user clicks on the plus sign, a row with identical content s ...

Ensure the padding and margin are both set to 0 when using inline styles

As someone who is not a designer, I attempted to send an email from PHP. In order to do so, I took a template and converted all styles to inline. However, I am unsure of where to include the universal margin and padding style in the template. *{margin:0px ...

Exploring the crossroads of MongoDB, Mongoose, and Node.js: An in-depth look

Searching for ways to retrieve references in MongoDB using Node.js and Mongoose. After reading the documentation, I discovered that there are two options available: Manual References or DBRefs. Given that Manual References are recommended, I proceeded to ...

Having trouble displaying dynamically generated texture from a fragment shader in ThreeJS

I've been working on creating a texture using a Three.WebGLRenderTarget and then trying to access it in a fragment shader in the following stage. The concept is to execute the first stage once to generate a complex and costly SDF map, and then access ...

Tips for recognizing the initial page load during the current execution of the JavaScript program

I am working on an ASP.net MVC project and I need to create a JavaScript function that will only execute on the initial load of the page during the current program run. If someone navigates to a different page and then returns, I do not want the function t ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

Can you please provide the CSS code that would style this table in a similar manner?

I am interested in utilizing the design of this table, but how can I update it to meet CSS standards and HTML5 equivalents? <html> <head></head> <body> <table border="1" bordercolor="#000000" style="background-color:#ffffff" w ...

Challenge with aligning tables

I need assistance with aligning the TD tag value to the TH tag value as I am currently experiencing alignment issues. Can someone please help me resolve this problem? I have attempted to fix it on jsfiddle Here is the HTML code: <table class=" ...