tomhoppe.com

Racing, Web Development, Photography, and Beer...Stuff that matters.

Tuesday, March 18, 2008

Dynamically adding CSS through Javascript

I found this little tip by accident while surfing the web to solve a different problem. Thanks to the Yahoo User Interface Blog for the solution!

When adding in a piece of HTML dynamically, what do you do with the styles for it? In the past, I usually included the styles in a global or page specific stylesheet where I knew the HTML would show up. The current snippet I was writing through, was going to add some code in random places throughout a 4000+ page website as well as some partner sites, so it needed to come with its own CSS. FF allows you nicely to just embed a <style> tag anywhere in a page with your styles and be done with it. IE and Safari, not so much.

What I found on the YUI Blog was the cssText property of the stylesheet property. This allows for a cross browser way for us to insert a string of css into a style element in the head. Beautiful! Just create your css as a string and pass it into the addCSS function below.

function addCss(cssCode) {
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}

Labels: , ,

1 Comments:

Anonymous Anonymous said...

thank you! I've been beating my head on the desk for an hour on this one. You rock.

August 25, 2008 at 1:40 PM  

Post a Comment

<< Home