The code doesn't:
It just makes one pass through document.styleSheets[0]. If once the code is put on the live page, that stylesheet is no longer the first on the page, that would explain it.
Since you don't want to have to count stylesheets, and id is an invalid attribute for stylesheets, you could use title, or ensure that this is the last stylesheet before the script and find it that way.
Using title:
Code:
<style type="text/css" title="menusheet">
.al {display:none}
.ca {display:none}
.ct {display:none}
.ga {display:none}
.il {display:none}
.la {display:none}
.ma {display:none}
.mi {display:none}
.mn {display:none}
.mo {display:none}
.ms {display:none}
.nc {display:none}
.ne {display:none}
.nh {display:none}
.nv {display:none}
.ny {display:none}
.or {display:none}
.sc {display:none}
.tn {display:none}
.tx {display:none}
.va {display:none}
.vt {display:none}
.wa {display:none}
.wi {display:none}
</style>
And then the script, which can go anywhere:
Code:
<script type="text/javascript">
function showHide(cls, show) {
// find the sheet:
for (var i = document.styleSheets.length - 1; i > -1; --i){
if(document.styleSheets[i].title === 'menusheet'){
showHide.sheet = document.styleSheets[i];
break;
}
}
// browser-compatibility
var rule = showHide.sheet.rules ? showHide.sheet.rules : showHide.sheet.cssRules;
for (var j = 0; j < rule.length; j++) {
if (rule[j].selectorText == "." + cls) { //find css selector
rule[j].style.display = (show) ? 'block' : 'none';
}
}
}
function selAction(sel) {
for (var i = 0; i < sel.options.length; i++) {
showHide(sel.options[i].value, i == sel.selectedIndex);
}
}
</script>
In this second method (determine the last sheet before the script), the stylesheet must be right before the script (additions/changes highlighted):
Code:
<script type="text/javascript">
function showHide(cls, show) {
// browser-compatibility
var rule = showHide.sheet.rules ? showHide.sheet.rules : showHide.sheet.cssRules;
for (var j = 0; j < rule.length; j++) {
if (rule[j].selectorText == "." + cls) { //find css selector
rule[j].style.display = (show) ? 'block' : 'none';
}
}
}
function selAction(sel) {
for (var i = 0; i < sel.options.length; i++) {
showHide(sel.options[i].value, i == sel.selectedIndex);
}
}
showHide.sheet = document.styleSheets[document.styleSheets.length - 1];
</script>
The browser cache may need to be cleared and/or the page refreshed to see changes.
There could be other problems.
If you want more help, please post a link to the page on your site that contains the problematic code so we can check it out.
Bookmarks