Skip to content

Instantly share code, notes, and snippets.

@szanata
Created December 29, 2015 15:43
Show Gist options
  • Save szanata/08d4e0e07877714e8024 to your computer and use it in GitHub Desktop.
Save szanata/08d4e0e07877714e8024 to your computer and use it in GitHub Desktop.
Dynamically create css rules
var CssRules = (function (){
var sheet = (function() {
// Create the <style> tag
var style = document.createElement("style");
// Add a media (and/or media query) here if you'd like!
// style.setAttribute("media", "screen")
// style.setAttribute("media", "only screen and (max-width : 1024px)")
// WebKit hack :(
//style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})(), cssRuleSets = [];
function rulesToString(rules) {
var a = [];
for (var p in rules) {
a.push('{0}:{1};'.format(p, rules[p]));
}
return a.join('');
}
var methods = {
append: function (selector, rules){
var rs = cssRuleSets[selector];
if (rs) {
rs.rules = rules;
sheet.deleteRule(rs.index);
} else {
cssRuleSets[selector] = {
rules: rules,
index: sheet.cssRules.length
}
rs = cssRuleSets[selector];
}
sheet.insertRule('{0} {{1}}'.format(selector, rulesToString(rs.rules)), rs.index);
}
}
return methods;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment