Skip to content

Instantly share code, notes, and snippets.

@mseeley
Created March 23, 2012 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mseeley/2173606 to your computer and use it in GitHub Desktop.
Save mseeley/2173606 to your computer and use it in GitHub Desktop.
Easily alter CSS rules via JS
// Allows programmatic altering of CSS rules. Turn this class into a flyweight by enabling modification of the underlying rule property.
function CssRule (selector, stylesheet) {
var rules = stylesheet.rules,
len = rules.length,
i = 0,
rule = null;
for (i; i < len; i++) {
rule = rules[i];
if (rule.selectorText === selector) {
this.rule = rule;
break;
}
}
}
CssRule.prototype = {
rule: null,
set: function (key, value) {
this.rule.style[key] = value;
return value;
},
get: function (key) {
return this.rule.style[key];
},
destroy: function () {
delete this.rule;
}
};
/*
Example:
<style type='text/css'>
.anim {
-webkit-transition-duration:300ms;
}
</style>
<script>
var anim = new CssRule('.anim', document.stylesheets[0]);
anim.get('webkitTransitionDuration'); // '300ms'
anim.set('webkitTransitionDuration', '100ms'); // '100ms'
</script>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment