Switching Style Sheets (Part IV)

Last time I explained how the javascript that we can use to change the stylesheet. What we need to do next is to make the user’s choice persistent all across the website, which means, it should be applied to all other documents, and the way to do this is to make use of cookies.

We need create a function that will return the current stylesheet and functions for reading and storing the cookie.

The first function can be implemented by looping through all the link elements, then three checks: check if the link is a stylesheet, check if it’s a preferred or an alternate style sheet and lastly check if the style sheet is active. Then we return the title if all the three checks are satisfied.

This is the function:

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

then we create the function createCookie and readCookie to store and read cookies, respectively.

The functions for the cookies can be implemented as:

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

and

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
To finish, we will need to add event listeners (onload and onunload) to the window. This will be discussed next.

 

Go back