Creating a custom CSS method.

+1 josh butts · March 8, 2015
How do I create my own css function? I know this is already included in jQuery but I am interested in how the syntax would work.

I want to create something like this for example... 


function css(userproperty, uservalue){ 
style.userproperty = uservalue; 
} ;


var body = document.getElementById('body'); 
body.css('background', 'color') 




obviously it's completely wrong, especially since I didn't even create an object for it, but I think if I can figure out how to do something like this, It would help me get a better grasp on objects and methods.

Post a Reply

Replies

Oldest  Newest  Rating
0 Jason Knight · March 8, 2015
Will this do?

          function addStylesheetRules (rules) {
                  var styleEl = document.createElement('style'),
                      styleSheet;
                  styleEl.appendChild(document.createTextNode(''));
                  document.head.appendChild(styleEl);
                
                  styleSheet = styleEl.sheet;
                
                  for (var i = 0, rl = rules.length; i < rl; i++) {
                    var j = 1, rule = rules[i], selector = rules[i][0], propStr = '';
                    if (Object.prototype.toString.call(rule[1][0]) === '[object Array]') {
                      rule = rule[1];
                      j = 0;
                    }
                
                    for (var pl = rule.length; j < pl; j++) {
                      var prop = rule[j];
                      propStr += prop[0] + ':' + prop[1] + (prop[2] ? ' !important' : '') + ';\n';
                    }
                
                    styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);
                  }
       }

Then use it like this. 


addStylesheetRules([
       ['.yourel',
         ['background', 'colour', true]
       ]
]);

Notice: This isn't my code it's from MDN. (I think) or maybe a gist.
0 Jason Knight · March 8, 2015
dam it, replace where it says 'https://www.thenewboston.com/images/emoticons/wink.png' with ') ;'
  • 1

Javascript

107,354 followers
About

A scripting language that is added to standard HTML to create interactive effects, apps, games for the browser.

Links
Moderators