Helpme Helpme - 7 months ago 112
CSS Question

Add new @keyframes animation to css

I can not add a new animation to css. Do you know what the solution can be?

var val = "@keyframes animation{0%{color:red;}100%{color:blue;}}";
var styleAnim = document.styleSheets[0];
styleAnim.insertRule(val, document.styleSheets[0].cssRules.length);
//Error:
Uncaught DOMException: Failed to execute 'insertRule' on 'CSSStyleSheet': Failed to parse the rule '@keyframes animation{0%{color:red;}100%{color:blue;}}'

Answer Source

You cant just update the rule (of animation keyframes) apparently. You need to remove it first and then add a new one. See fiddle: https://jsfiddle.net/Lmj7y5vm/2/

Assuming keyframes is the last rule in your stylesheet, and that you have it written in stylesheet with index 1 (that setting works for jsFiddle):

document.styleSheets[1].deleteRule(document.styleSheets[1].cssRules.length-1);
document.styleSheets[1].insertRule(newRule, document.styleSheets[1].cssRules.length-1);

Try clicking the paragraph.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download