Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically apply CSS definitions to the whole page?

Tags:

javascript

css

I'm sure the information already exists, but I couldn't find it; sorry :-/

I want to create CSS rules using JavaScript, and apply them to the whole page, as if they were in a style element in the document's head. I don't want to do it by generating the CSS text - I want to keep the rules as entities (JavaScript variables) that I can change, thus changing the appearance of the page later on.

Any help will be most appreciated!

like image 206
Tom Avatar asked Apr 15 '12 13:04

Tom


2 Answers

I've found what I wanted: http://www.javascriptkit.com/dhtmltutors/externalcss3.shtml .

(Thanks to all who've answered and commented. What I wanted - and finally found, see the link above - was an actual CSS-rule object that I could work with dynamically, like with HTML elements. While some of the answers came close, none of them was exactly it.)

like image 96
Tom Avatar answered Sep 29 '22 21:09

Tom


Depending on your needs if you need a quick and dirty way to edit css here is something that might work for you. You could simplify it some or even expand on it.

function css(){
  rules={};
  ref=//get a reference to a style element
  function setRules(){
    var out='';
    for(var x in rules){
      out+=x+'{'+rules[x]+'}';
    }
    ref.innerHTML=out;
  }
  this.addRule=function(ident,styles,values){
    var a;
    if(rules[ident]){
      a=rules[ident];
    }
    else{
      a = new cssR();
      rules[ident]=a;
    }
    if(styles.push){
      var i=0;len=styles.length;
      for(i;i<len;i++){
        a[styles[i]]=values[i];
      }
    }
    else{
      a[styles]=values;
    }
    rules[ident]=a;
    setRules();
  }
  function cssR(){

  }
  cssR.prototype.toString=function(){
    var out='';
    for(var x in this){
      typeof this[x]=='function'?'':out+=x+':'+this[x]+';';
    }
    return out;
  }
}
var a=new css();
a.addRule('#main','color','red');
a.addRule('#main','top','0px');
a.addRule('div .right','float','left');
a.addRule('div .right',['float','width'],['right','100px']);
like image 25
qw3n Avatar answered Sep 29 '22 19:09

qw3n