Sunday, 8 May 2011

Dynamcially adding style

Dynamically add style to a page...

var style = "body{color:#666;}";
var s = document.createElement('style');
s.setAttribute("type", "text/css");
if (s.styleSheet) { // IE
s.styleSheet.cssText = style;
} else {
var stxt = document.createTextNode(style);
s.appendChild( stxt );
}
document.getElementsByTagName('head')[0].appendChild(s);

Remember to minify the style text using something like http://refresh-sf.com/yui/
 

Note: the opinions on this page don't represent that of my employer in anyway. And, actually only vaguely represent my opinions on the date of publication. (Unlike Ms T, I am very much for turning)