JavaScript Style Switcher

JavaScript Style Switcher
When you create your CSS styles for a website you will have at least one style sheet for your layout and maybe another one for content, etc. (or just all in one). No matter how you organize your styles, every user will see your content the same.
Question: Can you give visitors a choice on how to view your content?
Answer: A JavaScript-powered style switcher is one way.
There are many websites today that have some form of “style switchers” that allow the user to switch the layout of specific element(s) by selecting from a drop down or clicking from a list of radio buttons for example. Most are just for simple font changes (small to normal to bigger), but some allow a totally new design to be available as well.
The code for this style switcher was used from a great article (.pdf) on A List Apart, written by Paul Swoden.
How it works is that you have multiple “alternative” style sheets each having a unique identifier (your hook). Then javascript code parses through your web page matching the style that was selected by the user and loads it accordingly.
function setActiveStyleSheet(title) {
 
var i, a, main;
 
for(i=0; (a = document.getElementsByTagName(“link”)[i]); i++) {
 
// is it a stylesheet?
if(a.getAttribute(“rel”).indexOf(“style”) != -1
 
// has a title attribute?
&& a.getAttribute(“title”)) {
 
a.disabled = true; // disable stylesheet
 
// Matches the passed alternative style name?
// if so re-enable it
if (a.getAttribute(“title”) == title) {
 
a.disabled = false;
}
}
}
}
 
// Sets the default stylesheet (rel=”stylesheet”).
// note: the main.css is your “sticky” stylesheet
// (no title attribute)
function getPreferredStyleSheet() {
 
var i, a;
 
for(i=0; (a = document.getElementsByTagName(“link”)[i]); i++) {
 
// Returns default stylesheet with title attribute
if(a.getAttribute(“rel”).indexOf(“style”) != -1
&& a.getAttribute(“rel”).indexOf(“alt”) == -1
&& a.getAttribute(“title”)) {
 
return a.getAttribute(“title”);
}
 
return null; // if no “link” elements found, return null
}
}
 
// Gets the ‘active’ stylesheet that is defined in HTML
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;
}
}
It also saves that selection in a cookie so when navigating to other pages that alternative style sheet will continued to be used and when the user revsits the site later.
Download the code from the downloads page.

Aly Chiman

Aly Chiman is a Blogger & Reporter at AlyChiTech.com which covers a wide variety of topics from local news from digital world fashion and beauty . AlyChiTech covers the top notch content from the around the world covering a wide variety of topics. Aly is currently studying BS Mass Communication at University.