Created
February 18, 2015 19:28
-
-
Save pgarciacamou/8b150065b43aef8b63e3 to your computer and use it in GitHub Desktop.
CSSRule is a constructor that allows to create classes on the run, it detects the prefix needed and you can use it by sending a callback function instead of a string to the add method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var CSSRule = (function (){ | |
var prefix = (function getPropertiesPrefix(){ | |
var t, el = document.createElement("fakeelement") | |
,animations = { | |
"animation": "", | |
"OAnimation": "-o-", | |
"msAnimation": "-ms-", | |
"MozAnimation": "-moz-", | |
"WebkitAnimation": "-webkit-" | |
}; | |
for(t in animations) if(el.style[t] !== undefined){ | |
return animations[t]; | |
} | |
})(); | |
function CSSRule(name){ | |
this.name = name.trim(); | |
this.rules = {}; | |
} | |
Object.defineProperties(CSSRule.prototype, { | |
'add': { | |
value: function (prop, val){ | |
if(typeof prop === 'function'){ | |
prop.call(null, prefix, this.rules); | |
} else this.rules[prop] = val; | |
return this; | |
} | |
} | |
,'create': { | |
value: function (){ | |
var rule = this.name + ' { '; | |
for(var prop in this.rules) if(this.rules.hasOwnProperty(prop)) { | |
rule += prop + ': ' + this.rules[prop] + ';'; | |
} | |
rule += ' }'; | |
if( document.styleSheets && document.styleSheets.length ) { | |
document.styleSheets[0].insertRule(rule, 0); | |
} else { | |
var s = document.createElement( 'style' ); | |
s.innerHTML = rule; | |
document.head.appendChild(s); | |
} | |
return null; // we return null because once created, we don't need to change it | |
} | |
} | |
}); | |
return CSSRule; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment