How to dynamically create '@-Keyframe' CSS animations? - GeeksforGeeks

31 Aug, 2020
In order to dynamically allocate keyframe animations to our HTML web-page, we are going to use the CSS stylesheets insertRule() method. We are going to take keyframes animation from a text area and then we will apply those rules to our web-page.
insertRule() method: This method is use to insert some new CSS rule into the current CSS style sheet(bound with some restriction).
Syntax:
stylesheet.insertRule(rule [, index])
Parameter: The method accepts two parameters as mentioned above and described below:
Rule: A DOMstring which is essentially the CSS rule to be inserted.
Rule: A DOMstring which is essentially the CSS rule to be inserted.
index(optional): The index at which the rule is inserted in CSSStyleSheet.cssRules
index(optional): The index at which the rule is inserted in CSSStyleSheet.cssRules
Example:
HTML: First, let’s make the layout structure of our page using HTML and CSS.htmlhtml<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"         content="width=device-width,                  initial-scale=1.0"></head><body>  <h2 style="color: green;">GeeksforGeeks</h2>  <div id="element"></div>  <form id="input">    <textarea id="text" rows="10" cols="40"></textarea><br>    <button type="submit">ADD ANIMATION</button>  </form>  <style>    #element{      width: 200px;      height: 200px;      background-color: green;      margin-bottom: 5px;    }  </style></body>
html
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"         content="width=device-width,                  initial-scale=1.0"></head><body>  <h2 style="color: green;">GeeksforGeeks</h2>  <div id="element"></div>  <form id="input">    <textarea id="text" rows="10" cols="40"></textarea><br>    <button type="submit">ADD ANIMATION</button>  </form>  <style>    #element{      width: 200px;      height: 200px;      background-color: green;      margin-bottom: 5px;    }  </style></body>
Output: The structure will look like.
JavaScript: Now, We are going to input a keyframe animation in the text area above and add it to the element that we have created.javascriptjavascript// Javascript code to add keyframeslet styleSheet = null;dynamicAnimation = (name,styles) => {// Creating a style element// To add the keyframesif (!styleSheet){  styleSheet = document.createElement('style');  styleSheet.type = 'text/css';  document.head.appendChild(styleSheet);}// Adding The KeyframesstyleSheet.sheet.insertRule(`@keyframes ${name} {${styles}}`,styleSheet.length);}   const form = document.getElementById("input");const text = document.getElementById("text");form.addEventListener('submit', (e)=>{  e.preventDefault()  // Adding an animation  // NewAnimation, with the   // Keyframes to the Stylesheet  dynamicAnimation('newAnimation', text.value);  // Timing and duration can be altered  // As per user requirements  document.getElementById("element").style.animation =   'newAnimation 3s infinite';});
javascript
// Javascript code to add keyframeslet styleSheet = null;dynamicAnimation = (name,styles) => {// Creating a style element// To add the keyframesif (!styleSheet){  styleSheet = document.createElement('style');  styleSheet.type = 'text/css';  document.head.appendChild(styleSheet);}// Adding The KeyframesstyleSheet.sheet.insertRule(`@keyframes ${name} {${styles}}`,styleSheet.length);}   const form = document.getElementById("input");const text = document.getElementById("text");form.addEventListener('submit', (e)=>{  e.preventDefault()  // Adding an animation  // NewAnimation, with the   // Keyframes to the Stylesheet  dynamicAnimation('newAnimation', text.value);  // Timing and duration can be altered  // As per user requirements  document.getElementById("element").style.animation =   'newAnimation 3s infinite';});
Implementation Code:
html
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"         content="width=device-width,         initial-scale=1.0"></head><body>  <h2 style="color: green;">GeeksforGeeks</h2>  <div id="element"></div>  <form id="input">    <textarea id="text" rows="10" cols="40"></textarea><br>    <button type="submit">ADD ANIMATION</button>  </form>  <style>    #element{      width: 200px;      height: 200px;      background-color: green;      margin-bottom: 5px;    }  </style>  <script>    let styleSheet = null;    dynamicAnimation = (name,styles) => {    if (!styleSheet){      styleSheet = document.createElement('style');      styleSheet.type = 'text/css';      document.head.appendChild(styleSheet);    }      styleSheet.sheet.insertRule(`@keyframes ${name} {${styles}}`,    styleSheet.length    );    }      const form = document.getElementById("input");    const text = document.getElementById("text");    form.addEventListener('submit', (e)=>{      e.preventDefault();      console.log("submitted");      console.log(text.value);        dynamicAnimation('newAnimation', text.value);      document.getElementById("element").style.animation =                                 'newAnimation 3s infinite';    });  </script></body></html>
CSS:Now, We are going to add the following Keyframe Rule Set to the text box element.
CSS
25%{    transform : translateX(25%);    border-radius : 25%;   }50%{    transform : translateX(50%);    border-radius : 50%;   }75%{    transform : translateX(25%);    border-radius : 25%;}100%{    transform : translateX(0%);    border-radius : 0%;}
Output:
Before Submitting Keyframes:
Before Submitting Keyframes:
After Submitting Keyframes:
After Submitting Keyframes:
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to Upload Image into Database and Display it using PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript