Working JavaScript for Dynamic Stylesheet Changing

  • From: "Bryan Garaventa" <bgaraventa11@xxxxxxxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Sun, 17 Feb 2008 00:13:31 -0800

I wrote this to bypass a particularly irritating html editor, which would overwrite my style tag changes every time I published the page. So, this script will dynamically change the main style tag when the page loads, and add the desired style rule or rules as desired on any page.


The implementation of this being at http://gutterstar.net/footer.js

// How to use the Dynamic Style Changer
// Syntax Examples
// changeRule('Tag', 'Property', 'Value');
// changeRule('P', 'color', '#000000');
// Important: Do not include a dash, instead, do the following for such properties
// changeRule('H2', 'fontSize', '15pt');

var sheet;

function changeRule(selector, ruleN, ruleV) {

if (!sheet) {
if (document.styleSheets.length) {
sheet = document.styleSheets[0];
} else {
sheet = document.createStyleSheet();
}
}

var rules;
rules = sheet.cssRules || sheet.rules;
for (var j = 0; j < rules.length; j++) {
if (rules[j].selectorText == selector) {
if (sheet.rules) {
eval('sheet.rules[j].style.' + ruleN + ' = "' + ruleV + '"');
}
else if (sheet.cssRules) {
eval('sheet.cssRules[j].style.' + ruleN + ' = "' + ruleV + '"');
}
return;
}
}

if (sheet.insertRule) { // firefox
sheet.insertRule('' + selector + ' { ' + ruleN + ': ' + ruleV + ' }', sheet.cssRules.length);
}
else if (sheet.addRule) { // IE
sheet.addRule(selector, ruleN + ': ' + ruleV);
}

}

// End of code

Bryan Garaventa
__________
View the list's information and change your settings at //www.freelists.org/list/programmingblind

Other related posts:

  • » Working JavaScript for Dynamic Stylesheet Changing