How to Add CSS Animation with JavaScript
A JavaScript snippet to dynamically add shorthand CSS animation property to any element. Useful method to insert an animation on a certain scenario. The syntax used in JavaScript code is similar with one in CSS.
Syntax
Standard browsers
document.getElementById("myDiv").style.animation = "[animation_name] [Duration] [TimingFunction] [Delay] [IterationCount] [Direction] [fillMode] [playState]";
Safari 4.0-8.0
document.getElementById("myDIV").style.WebkitAnimation = "[animation_name] [Duration] [TimingFunction] [Delay] [IterationCount] [Direction] [fillMode] [playState]";
Note
For detailed description about each property, refer to MDN Web Docs
Example Snippet 1
document.getElementById("myDiv").style.animation = "myAnimation 1s ease infinite";
Note
myAnimation is a defined animation with @keyframes rule.
If you also want to dynamically insert @keyframes rule with JavaScript, you can use CSSStyleSheet.insertRule() method. See snippet below.
const css = window.document.styleSheets[0]; css.insertRule(` @keyframes myAnimation { 0% { left: 0; } 50% { left: 100px; } 100% { left: -100%; } }`, css.cssRules.length);
Note
There are some restrictions when using CSSStyleSheet.insertRule(). See more detail in this MDN document.
Example Snippet 2
Adding 5 seconds animation loop when “myDiv” element is clicked.
document.getElementById("myDiv") .addEventListener("click", function() { this.style.animation = "myAnimation 5s ease infinite"; });