0

I have a web page that links to several pure CSS animation libraries, and I may add more in future. I want to be able to randomly select an animation from all available ones. I can't figure out how to get a list of the keyframe names in JavaScript so that I can pick one and use it. My typical CSS element looks like animation-name: <<keyframe name>>;

Can someone share the code to do this?

Heretic Monkey
  • 11,078
  • 7
  • 55
  • 112
Mark Kortink
  • 1,342
  • 1
  • 16
  • 22

1 Answers1

1

The following script will get all the animations in all CSS sheets and store them into an array.


function getAnimationList(){
// Return a list of all of the animation keyframes in all style sheets.
    var ss = document.styleSheets;
    var anims = [];
    // loop through all the style sheets
    for (var s = 0; s < ss.length; s++) {
        if (ss[s].cssRules) {
            // loop through all the rules
            for (var r = ss[s].cssRules.length - 1; r >= 0; r--) {
                var rule = ss[s].cssRules[r];
                if ((rule.type === window.CSSRule.KEYFRAMES_RULE || rule.type === window.CSSRule.WEBKIT_KEYFRAMES_RULE)) {
                    anims.push(rule);
                }
            }
        }
    }
    return anims;
};

// Write all the animation (keyframe) names to the console.
animList = getAnimationList();
if (animList.length == 0){
    console.log('>>> No Animations');
} else {
    console.log('>>> Number of animations is ' + animList.length);
    for (var a = 0; a < animList.length; a++) {
        console.log('>>> ' + animList[a].name);
    };
};

One problem I did encounter is that many browsers have now implemented cross-domain constraints that include CSS files. If you want to search some CSS style sheets on another domain your browser may object. Refer to this as a starting point.

Also note that the reason I decrement through the rules is explained here.

Mark Kortink
  • 1,342
  • 1
  • 16
  • 22
  • Since you put all rules in an array anyway instead of returning only the first you find, I don't think you need to iterate backwards. – Bergi Dec 12 '20 at 22:56
  • @Bergi good point, agree, worth noting though if you want to use the array to name search. – Mark Kortink Dec 12 '20 at 23:17