Skip to content

Instantly share code, notes, and snippets.

@AlyxRen
Created October 15, 2010 18:43
Show Gist options
  • Save AlyxRen/628711 to your computer and use it in GitHub Desktop.
Save AlyxRen/628711 to your computer and use it in GitHub Desktop.
/*
Copyright 2010 Stephen "Rixius" Middleton
Licensed under the MIT-style License <http://www.opensource.org/licenses/mit-license.html>
usage Style(Object styleRules, object Options)
Options: { //with defaults
makeStyle: true, //if true makes the <style> elment and wraps it around the styles
placeInDOM: false, //if true, if makeStyle is true, then places the elemen ad the of the <head> element
important: false //appends " !important" at the end of each declration, Just in case it's needed;
}
styleRules: {
'element': {
'rule': 'value'
},
'a[href=google.com]': {
'color': 'red'
},
'a, p': {
'color': 'blue'
}
}
*/
(function() {
var exports, extend, managePlugin, obj2string, options;
var __slice = Array.prototype.slice, __hasProp = Object.prototype.hasOwnProperty;
exports = this.exports || this;
extend = function() {
var _a, _b, _c, _d, inp, key, oput, val, val2;
inp = __slice.call(arguments, 0);
oput = {};
_b = inp;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
val = _b[_a];
if (val) {
_d = val;
for (key in _d) {
if (!__hasProp.call(_d, key)) continue;
val2 = _d[key];
oput[key] = val2;
}
}
}
return oput;
};
obj2string = function() {
var _c, _d, data, k, k2, objs, output, tempStr, v, v2;
var _a = arguments.length, _b = _a >= 2, opt = arguments[_b ? _a - 1 : 0];
objs = __slice.call(arguments, 0, _a - 1);
data = extend.apply(extend, objs);
output = "";
_c = data;
for (k in _c) {
if (!__hasProp.call(_c, k)) continue;
v = _c[k];
tempStr = k + " {\n";
_d = v;
for (k2 in _d) {
if (!__hasProp.call(_d, k2)) continue;
v2 = _d[k2];
if (opt.important) {
tempStr += ' ' + k2 + ': ' + v2 + " !important;\n";
} else {
tempStr += ' ' + k2 + ': ' + v2 + ";\n";
};
}
output += tempStr + "}\n";
}
return output;
};
options = {
makeStyle: true,
placeInDOM: false,
important: false
};
managePlugin = function(inpObj, opt) {
var elem, txtN, tempStr;
opt = extend(options, opt);
tempStr = obj2string(inpObj, opt);
if (opt.makeStyle) {
elem = document.createElement('style');
elem.setAttribute('type','text/css');
if(elem.styleSheet) { // IE does it this way
elem.styleSheet.cssText = tempStr
} else { // everyone else does it this way
elem.appendChild(document.createTextNode(tempStr));
}
//elem.innerHTML = tempStr;
if (opt.placeInDOM) {
return (document.getElementsByTagName('head')[0]).appendChild(elem);
}
return elem;
} else {
return tempStr;
}
};
this.Style = managePlugin;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment