Switching Style Sheets (Part III)

This is the third part of a series of post on dynamic switching of style sheets. The first post discussed the basic CSS knowledge required, and the second post discussed the background on style sheet switching and why it has to be implemented in javascript.

The script is a simple one, with three main building blocks:

a way to check if the link element is a link to a style sheet,

       HTMLLinkElement.getAttribute("rel").indexOf("style") != -1

a way to check if the title attribute is defined, and


if the rel attribute contains the word “alt”

       HTMLLinkElement.getAttribute("rel").indexOf("alt") != -1

We then use the three javascript checks above to create our style sheet switching javascript method. To do this, we loop through all the link elements in the document and disables all the preferred and alternate style sheets that the user did not select and enables all the preferred and alternate style sheets that the user selected. Below is one implementation of the switching function:

function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;

The method above already implements the switching mechanism that we want. But what if the user goes to another part of the website after selecting a desired style sheet? At this point, the preferred style sheet will be enabled regardless of the user’s choice. This creates a problem of not giving a whole personalized experience. What we need is a mechanism to make the user’s choice style sheet persistent. This can be done through the use of cookies to store the user’s preferences.

Next time I will discuss the other scripts that needs to be implemented to address this issue.

Go back