ert3
ert3

Reputation: 114

Adding a style sheet IE 8 with JavaScript

I'm making a zoom button to add and remove a CSS file and for some reason I can't seem to add it in IE 8

First I tried this

document.createStyleSheet('style/zoom.css');

given that the jquery solution

$("head").append($("<link my style sheet />"));

seems to only work in FF and IE9 via my testing

I checked around the overflow and found this solution

 $('#zoomlink').replaceWith($('<link>', {
        id: 'zoomlink',
        href: 'style/zoom.css',
        type: 'text/css',
        rel: 'stylesheet' 
 }));

But still no love to be found so then frustrated i found this

var $link = $('&lt;link&gt;');
    $('head').add($link);
    $link.attr({
      type: 'text/css',
      href: 'style/zoom.css',
      type: 'text/css',
      rel: 'stylesheet',
      media: 'screen'
});

which im not certain would ever work but then finally i decided it way time to simply post a question.

I'm still not certain on how to remove the style sheet later via javascript but I need to first determine how to add a new style sheet in IE 8.

Upvotes: 1

Views: 2027

Answers (2)

Nope
Nope

Reputation: 22339

To remove it I would assume a simple remove() would work

$("#zoomlink").remove();

To add a new link using jQuery with this syntax:

$("head").append(unescape("%3Clink id='zoomlink' rel='stylesheet' type='text/css' href='style/zoom.css'%3E%3C/link%3E"));

or using pure JavaScript

var e = document.createElement('link');
e.id = 'zoomlink'
e.rel = 'stylesheet';  
e.type='text/css';
r.href='style/zoom.css'
document.getElementsByTagName("head")[0].appendChild(e);

There is many other way of writing the same but the idea is the same, remove the old reference element and add a new one.

Upvotes: 1

Igor Shastin
Igor Shastin

Reputation: 2888

Maybe this will help (Sorry, can't try it in IE8):

(function() {
    var s  = document.createElement('link');
    s.type = 'text/css';
    s.rel  = 'stylesheet';
    s.href = 'http://yourdomain.com/style.css';
    document.getElementsByTagName("head")[0].appendChild(s);
})();

Upvotes: 4

Related Questions