Switching Style Sheets (End)


In the onload function, we need to apply the user’s style sheet of choice either from the cookie when it exists or  just use the preferred style sheet when the cookie has not yet been created.

We therefore need to implement a getPreferred StyleSheet function to return the title of a preferred style sheet. It does this by finding the style sheet with a title but whose rel attribute is not “alt”.

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  return null;

Since the value of the title attribute of the style sheet that will be used for the document can either come from the cookie or from the preferred style sheet returned by the getPreferredStyleSheet function, we first need a title variable in our onload function.

window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();


It is in the onunload function where we need to save the cookie. This can be easily done by calling the getActiveStyleSheet() function and saving the returned value to a cookie.

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);

I have just finished showing the building blocks of a cross-platform style sheet switching mechanism. Now all you have to is to include the javascript methods in your document. You can put it an a single external javascript file and add it to your document using the script element:

<script type="text/javascript"


Go back