View Full Version : Javascraipt stylesheet switcher help to improve

07-27-2009, 04:46 PM
Hiya, I was wondering if you could give me a few tips/ideas. I have a stylesheet switcher on my website which works ok, the problem is refining it as there are a couple of things that aren't so great...

First of all, once the stylesheet has been changed to one that is not the default, when I click on another page or refresh, the default styles load first and then change to the new stylesheet that's been set. I think this has to do with the order the page is loading in. Ideally I'd obviously want the new set style to kick in right away on each page so there's a smooth transition between pages. My other concern is that once I have changed to another stylesheet and I change back to the default, if I go onto another page or click refresh it goes back to the previous non-default stylesheet instead of sticking to the default one I've just changed it to.

Any ideas would be greatly appreciated, thanks for your time!


<script type="text/javascript">

function changeStyleSheet(title) {
var links = document.getElementsByTagName("link");
for(var i = 0; i < links.length; i++) {
if(links[i].getAttribute("title")) links[i].disabled = true;
if(links[i].getAttribute("title") == title) {
links[i].disabled = false;
var expires = new Date();
expires.setTime(expires.getTime() + (30*24*60*60*1000));
document.cookie = "stylesheet="+title+";expires="+expires.toGMTString()+";path=/";

function getStylesheetFromCookie() {
var cookie = document.cookie.split(";");
for(var i = 0; i < cookie.length; i++) {
var values = cookie[i].split("=");
if (values[0] == "stylesheet") changeStyleSheet(values[1]);





<link type="text/css" rel="stylesheet" href="default.css" />
<link type="text/css" rel="alternate stylesheet" href="alt.css" title="alt" />


<body onload="getStylesheetFromCookie()">

<li><a href="#" onclick="changeStyleSheet('default')" title="default">default</a></li>
<li><a href="#" onclick="changeStyleSheet('alt')" title="alt">alt</a></li>