Skip to content

Instantly share code, notes, and snippets.

@dryan
Created May 20, 2011 20:48
Show Gist options
  • Save dryan/983765 to your computer and use it in GitHub Desktop.
Save dryan/983765 to your computer and use it in GitHub Desktop.
Method for inserting dynamic CSS via JavaScript/jQuery
/*
Based on work by Aaron Gustafson <http://easy-designs.net>
Requires jQuery
*/
(function($) {
$('<style id="inline-css" media="screen"></style>').appendTo('head');
var style = $('#inline-css').get(0);
function addCSSRule(rule) {
var newRules = {},
oldRules = {},
newRulesArray = rule.split('{', 2),
selector = $.trim(newRulesArray[0]),
oldRuleIndex = null;
newRulesArray = $.trim(newRulesArray[1].replace(/([\s]+)?\}([\s]+)?$/, '')).split(';').reverse();
for (var i = newRulesArray.length - 1; i >= 0; i--) {
var newRule = newRulesArray[i];
if(newRule.length) {
newRule = newRule.split(':', 2);
newRules[$.trim(newRule[0])] = $.trim(newRule[1]);
}
};
for (var i = style.sheet.cssRules.length - 1; i >= 0; i--) {
var oldRule = style.sheet.cssRules[i];
if(oldRule.selectorText == selector) {
oldRuleIndex = style.sheet.cssRules.length - 1 - i;
for (var i = oldRule.style.length - 1; i >= 0; i--){
oldRules[oldRule.style[i]] = oldRule.style[oldRule.style[i]];
};
}
};
newRules = $.extend(oldRules, newRules);
rule = selector + ' { ';
for(var prop in newRules) {
rule = rule + prop + ': ' + newRules[prop] + '; ';
}
rule = rule + '}';
if(oldRuleIndex !== null) {
style.sheet.deleteRule(oldRuleIndex);
}
style.sheet.insertRule(rule, style.sheet.cssRules.length);
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment