Matt Greenberg
Matt Greenberg

Reputation: 2330

addRule / insertRule Not working locacly

I am building a javascript image slider and noticed a problem pulling up the index.html file locally in chrome. Here is my code

(function(){ //slider container

    var slider = document.getElementById('slider');
    var figure = slider.childNodes[1];
    var slidyImgs = figure.getElementsByTagName('IMG');
    var figureWidth = slidyImgs.length * 100;
    var slidyImgsWidth = 100 / slidyImgs.length;

    css('#slider figure{ width: '+figureWidth+"%; }"); 
    css('#slider figure img{ width: '+slidyImgsWidth+"%; }");

    var xPos = 100;
    setInterval(function(){
        figure.style.marginLeft = "-" + xPos + "%";
        xPos = (xPos === (figureWidth - 100)) ? 0 : xPos + 100;
    },7000);

})()

function css(newrule) { //adds a new style to stylesheet
    var styles = document.styleSheets[1]
    try { 
        styles.insertRule(newrule, styles.cssRules.length);
    } catch(err) {
        try { styles.addRule(newrule); }catch(err){} //IE
    };
};

When i open the file locally, the insertRule doesn't seem to be applied. But when i open it on my server, the insertRule appears as normal. Anyone got any idea whats causing this

you can view the website /source code on my server: http://magnetwd.com/kellin/

Upvotes: 1

Views: 832

Answers (1)

Jack
Jack

Reputation: 21183

I would do something like this instead (if jQuery isn't an option)

function addStylesBySelector(sel, newStyles) {
    var els = document.querySelectorAll(sel)
    for (var i = 0; i < els.length; i++) {
        for (var k in newStyles) {
            els[i].style[k] = newStyles[k];
        }
    }
}

Usage:

addStylesBySelector('#slider figure', {"width": figureWidth + "%"})

Then obviously you can add more than just width for the second argument.

Upvotes: 1

Related Questions