Call SEO0845 838 7448 SEO RSS Feed

Switching Style Sheets (Part IV)

May 312007

published by Dan in CSS | Tools & Resources | Web Technology | Website Design | Website Standards with No Comments

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.

AddThis Social Bookmark ButtonAddThis Feed Button

RSS feed | Trackback URI

No responses to Switching Style Sheets (Part IV)

No comments yet.

Leave a reply


You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> in your comment.

SEO Services | SEO Firm | SEO Consultant | UK Search Engine Optimisation | Search Engine Optimisation Services | Search Engine Marketing | Pay-Per-Click
Internet Marketing SEO | SEO Company | SEO Service | SEO Companies | SEO Promotion | SEO Strategy | SEO Peterborough | SEO Ranking

© 2007 Doublespark Limited - All rights reserved.

This site is protected by Copyscape