Last active
August 31, 2016 11:07
-
-
Save archatas/230841 to your computer and use it in GitHub Desktop.
Add CSS rules dynamically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add CSS rules dynamically | |
* Example: | |
* dyn_css_rule("#menu li:hover", "color: red") | |
*/ | |
window.dyn_css_rule = function(sSelector, sCssText) { | |
try { | |
var aSS = document.styleSheets; | |
var i; | |
for (i=aSS.length-1; i>=0; i--) { | |
var oCss = document.styleSheets[i]; | |
var sMedia = (typeof(oCss.media) == "string")? | |
oCss.media: | |
oCss.media.mediaText; | |
if (!sMedia | |
|| sMedia.indexOf("screen") != -1 | |
|| sMedia.indexOf("all") != -1 | |
) { | |
break; | |
} | |
} | |
if (oCss.insertRule) { | |
oCss.insertRule(sSelector + " {" + sCssText + "}", oCss.cssRules.length); | |
} else if (oCss.addRule) { | |
oCss.addRule(sSelector, sCssText); | |
} | |
} catch(err) { | |
var tag = document.createElement('style'); | |
tag.type = 'text/css'; | |
try { | |
tag.innerHTML = sSelector + " {" + sCssText + "}"; | |
} catch(err) { | |
tag.innerText = sSelector + " {" + sCssText + "}"; | |
} | |
document.getElementsByTagName('head')[0].appendChild(tag); | |
} | |
return sSelector + "{" + sCssText + "}"; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment