javascript add animation property
CSS Javascript

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.


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]";
For detailed description about each property, refer to MDN Web Docs

Example Snippet 1

document.getElementById("myDiv").style.animation = "myAnimation 1s ease infinite";
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];
@keyframes myAnimation {
  0%   { left: 0;     }
  50%  { left: 100px; }
  100% { left: -100%; }
}`, css.cssRules.length);
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.

.addEventListener("click", function() { = "myAnimation 5s ease infinite";


Leave a Reply

Your email address will not be published. Required fields are marked *