Css injector

by Paweł Niemczyk

HTML

<a href="#" id="on" > On  </a>
<a href="#" id="off"> Off </a>
<div id="test"></div>

CSS

#test{
    width: 100px;
    height: 100px;
    background-color: red;
    display:block;
}

CoffeeScript

cssStyleInjector = (cssText, id="default", elem="head") ->
  thisCss = document.getElementById(id)
  return thisCss.innerHTML = cssText  if thisCss?
  css = document.createElement("style")
  css.setAttribute "type", "text/css"
  css.setAttribute "id", id
  style = document.createTextNode(cssText)
  css.appendChild style
  document[elem].appendChild css

$('#on').click -> cssStyleInjector("#test{ background-color: blue; width: 100px;}")
$('#off').click -> cssStyleInjector("#test{ background-color: green; width: 150px;}")