Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.styleSheets returns nothing

I am using css3 animations to move items from one side of the screen to the other. I want to make sure this effect works regardless of screen resolution. In order to do this, I use document.styleSheets in order to get access to the css file with all of the animation keyframes and change their final values.

Here is the js code I am using:

var stylesheet = document.styleSheets[1];

var rules = stylesheet.rules;
var keyframes;
var keyframe;

for (var i = 0; i < rules.length; i++){
    keyframes = rules.item(i);

    var keyframeRules = keyframes.cssRules;
    var j = keyframeRules.length;
    var index = i+1;

    while (j--) {
        keyframe = keyframeRules.item(j);
        if (keyframe.keyText === "100%") {
            if(keyframe.style.left != ''){
                keyframe.style.left = $(document).width() + $('#cloud'+ index).width() + 'px';
            }
        }
    }

    $('#cloud'+ index).addClass('animating');
}

The css file I am using contains:

@-moz-keyframes cloud1 {
0%{ left: -400px; }
100%{ left: 0; }
}

@-webkit-keyframes cloud1 {
0%{ left: -400px; }
100%{ left: 0; }
}

I have quite a few pairs of keyframes in there.

My problem is document.styleSheets returns an empty css file if I console.log it and inspect in firebug. As a result, rules.length is null. Webkit based browsers work without any issues.

Am I missing something obvious here?

like image 369
boz Avatar asked Apr 19 '26 18:04

boz


1 Answers

Different browsers use different names to refer to those rules.

Here's how I handle this problem in my code :

var cssRules = stylesheet.rules; // chrome, IE
if (!cssRules) cssRules = stylesheet.cssRules; // firefox (and maybe Chrome too in recent versions)

You could do it as :

var cssRules = stylesheet.rules || stylesheet.cssRules; 

But I prefer the first version as it's clearer.

like image 71
Denys Séguret Avatar answered Apr 21 '26 06:04

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!