Friday 20 December 2013

Add Rule and Insert Rule methods Css stylesheet

Add Rule and Insert Rule methods :


 Sometimes we need to change our css rules dynamically. With Css-rules ,I mean to say style-definition of css classes and ids.
 We can add new rules to our predefined class using the insertRule and addRule (as reqd.) methods to add new rules to our css class 
 as is shown below:

 The addRule method accepts three arguments:  the selector, the second the CSS code for the rule, and the third is the zero-based integer 
 index representing the style position (in relation to styles of the same selector):

 sheet.addRule("#myId", "float: left; background: red !important;", 1);


 The CSSStyleSheet.insertRule() method inserts a new style rule into the current style sheet.

sheet.insertRule("#myId", "float: left; background: red !important;", 1);


function addCSSRule(sheet, selector, rules) {
if(sheet.insertRule) {
sheet.insertRule(selector + "{" + rules + "}", index);
}
else {
sheet.addRule(selector, rules, index);
}
//if -else is used because some browsers don't support insertRule and some don't support addRule
}
// we can use it as
addCSSRule(document.styleSheets[0], "header", "float: left");

Happy Coding!

No comments:

Post a Comment