0

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;}}'
3
  • Please post the complete @keyframes rule. Commented Nov 29, 2017 at 22:54
  • @Joulss try to see now Commented Nov 29, 2017 at 22:58
  • 1
    Weird, I tried and it works... See jsfiddle.net/ta10wx9a/2 Commented Nov 29, 2017 at 23:37

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.