So I'm trying to have a stylesheet switcher option on my page, where the user can click a radio button and it changes which stylesheet is being applied, but it's not working for me.
Here's what's in my head tag:
<link href="stylesheet.css" type="text/css" rel="stylesheet" title="main">
<link href="stylesheet2.css" type="text/css" rel="alternate stylesheet" title="alt1">
<link href="stylesheet3.css" type="text/css" rel="alternate stylesheet" title="alt2">
<script language="javascript">
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}
</script>
And here's the actual radio form:
<p><input type="radio" name="look" onClick="setActiveStyleSheet('main')" checked> Light & dark blue</p>
<p><input type="radio" name="look" onClick="setActiveStyleSheet('alt1')"> Black & white</p>
<p><input type="radio" name="look" onClick="setActiveStyleSheet('alt2')">Yellow & red</p>
Anyone mind telling me what I'm doing wrong? Thank you!
You should pass strings enclosed in quotes - otherwise JavaScript thinks they're variable names:
But your real problem is this:
sets
a
as an HTMLCollection object, not as the link itself. Change it to:And you'll be fine.
It seems alistapart isn't perfect after all.
variable
a
is array of elements, you should access its elemnts by index (ie.a[i]
) and not directly.also, the for loop condition should bei < a.length
.. . The disabling/enabling logic seems ok, but your for loop condition doesn't look good. Anyway, the problem is that the other stylesheets are still set as "alternative stylesheet". You should change that too.