Tuesday, December 23, 2008

Dynamically Adding Styles via JavaScript

This one is straight forward but then IE has to go and spoil the party. The idea is to create a style element and then append a text node containing your style information to it; then append the style element to the head of the page. Trouble is, IE blows up when you try to run createElement("style"). So you have to use MS' proprietary function. I won't bore you more, here is the code (replace YOURCSSTEXT):
var ss = null;
if(document.createStyleSheet) // IE
{
ss = document.createStyleSheet();
ss.cssText=YOURCSSTEXT;
} else { // All other browsers
ss = document.createElement("style");
ss.type="text/css"; ss.appendChild(document.createTextNode(YOURCSSTEXT));
document.getElementsByTagName("head")[0].appendChild(ss);
}

No comments:

Labels

Blog Archive

Contributors