PHPToExpert
PHPToExpert

Reputation: 21

Javascript Jquery Add StyleSheet IE

There is my code source :

            nodeCss = $('<link rel="stylesheet" href="about:blank" type="text/css" 

media="all" />');
                nodeCss.attr('href',css_file);
                $("head").append(nodeCss);

I have two problems on IE :

Sorry for my language, i speak a little english, be comprehensible.

Thanks a lot.

Upvotes: 2

Views: 2075

Answers (3)

Alex W
Alex W

Reputation: 38183

Adding a stylesheet dynamically with jQuery gives me a lot of issues in older versions of IE. Here's what I've ended up using that works cross-browser:

// Prevent Firefox security error
document.getElementsByTagName('head')[0].appendChild(document.createElement('style'));

// Get last style sheet so that the rules we add will take precedence
var sheet = document.styleSheets[document.styleSheets.length-1]; 


// Internet Explorer method
if(sheet.addRule)
{

    // FORMAT:
    // sheet.addRule('selector','rule: xxx');
    // sheet.addRule('selector','rule: xxx');

    sheet.addRule('a:hover','color: yellow');
    sheet.addRule('a:hover','text-decoration: none');

}

// All other browsers
if(sheet.insertRule)
{

    // FORMAT: sheet.insertRule('selector { rule: xxx; rule: xxx; rule: xxx; }');
    sheet.insertRule('a:hover { color: yellow; text-decoration: none; }', sheet.cssRules.length);
}

Upvotes: 0

duri
duri

Reputation: 15351

I won't answer directly to your question, because there are much more reliable and simpler ways how to achieve the desired effect.

If you want to dynamically load a CSS file appended to document using <link> element, just add it to your markup and set it the disabled attribute initially: <link rel=stylesheet href=style.css disabled>. All you have to do in JS/DOM is to set its DOM property disabled to false (boolean value). In jQuery, prop() method should be used to do this.

If your css_file variable can take more different values depending on some other code, the recommended solution is to change the class of <html> element. Then, you can easily use selectors like .state1 #selector and .state2 #selector to express different states in the HTML document.

Upvotes: 1

Justin Helgerson
Justin Helgerson

Reputation: 25521

Try using document.createStylesheet for IE browsers. MSDN has an article on how to use this method.

A potential cross browser solution:

(document.createStyleSheet) ? document.createStyleSheet(css_file) : $('<link rel="stylesheet" type="text/css" href="' + css_file + '" />').appendTo('head')

Upvotes: 2

Related Questions