4

I want to adjust a specific @keyframes-rule in my CSS with JavaScript. This all worked pretty well with the following code:

CSS:

@-webkit-keyframes changecolor {
    0% { color: red; }
    100% { color: green; }
}
@keyframes changecolor {
    0% { color: red; }
    100% { color: green; }
}

JavaScript:

function getKeyframeRule(ruleName) {
    var ss = document.styleSheets,
        rule, i, x;

    for (i = 0; i < ss.length; ++i) {
        if (ss[i].cssRules) {
            // loop through all the rules
            for (x = 0; x < ss[i].cssRules.length; ++x) {
                rule = ss[i].cssRules[x];
                if ((rule.type === window.CSSRule.KEYFRAMES_RULE || rule.type === window.CSSRule.WEBKIT_KEYFRAMES_RULE) && rule.name === ruleName) {
                    return rule;
                }
            }
        }
    }
    return null;
}

// find keyframes rule
var rule = getKeyframeRule("changecolor");
console.log(rule.cssText);

// adjust keyframes rule
// ...

Since Chrome 43 the browser supports unprefixed CSS animation properties. But my code still returns the prefixed keyframes rule @-webkit-keyframes changecolor because it also applies to the condition if ((rule.type === window.CSSRule.KEYFRAMES_RULE || rule.type === window.CSSRule.WEBKIT_KEYFRAMES_RULE) && rule.name === ruleName) {.

What's a better way to select the keyframes rule which is actually used by the browser?

Here is the full example: http://jsfiddle.net/tschortsch/zbma3bcp/2/

1 Answer 1

8

The keyframes rule used is the last to be defined. Therefore, you can loop from the end, instead of from the beginning:

for (x = ss[i].cssRules.length - 1; x >= 0; x--) {
    rule = ss[i].cssRules[x];
    if ((rule.type === window.CSSRule.KEYFRAMES_RULE || rule.type === window.CSSRule.WEBKIT_KEYFRAMES_RULE) && rule.name === ruleName) {
        return rule;
    }
}

See fiddle.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.