This post assumes some intermediate understanding of Javascript and stylesheets. It will show you how to setup a Javascript-powered styleswitcher that works for individual pages.

One of the huge benefits that CSS, or Cascading Style Sheets, brought to web design was the ability to easily change an entire website's design and layout. Since CSS allows a separation of content and layout, a single style sheet can control all of the pages of a website. Some extra markup in the HTML may be needed for specific layout requirements, but colors, font-size, and normal layout options can be easily modified with a few lines.

This brings up an interesting opportunity: multiple stylesheets for a web site. These different stylesheets can have simple changes: a main one containing layout and general styles with several optional sheets with color information. By attaching the stylesheets to the document with the alternate tag, some browsers will allow users to switch between the sheets under their 'View' menu.

In this example, I plan on using three stylesheets with one as default. The main_style.css has all of the style information, while black.css and yellow.css only has basic color information. I want main_style.css to load all of the time, but allow the user to choose to override some colors by choosing one of the other two styles. The best way to achieve this is with a small Javascript menu.

The Javascript menu is easily created. It won't actually link to anything, so we'll have to fill the href attribute with a default value. The id attached to each link, combined with the script, will do the actual linking to each stylesheet option.

The first function, loadEvents(), is called when the document loads. This can be done by adding an onload="loadEvents" to your body tag or by your own script's listeners. After the document loads, it attaches a 'click' listener to each link in the style_switch list, passing the id of the link to the setActiveStyleSheet function. The second attachEvent part of the function is for Internet Explorer.

The second function loops through all stylesheets listed in the document and disables them. This can be viewed as a 'reset' that is performed after every style switch. It then checks to see if the style is default (in my case, has a 'blue' id) or is the one requested (the id carried by the click to this function) and enables them.

This will set a stylesheet for an individual page, but does not save the user's preference. If they visit other pages on your web site or return to it later, the style defaults to the main sheet. Tomorrow's post will focus on this, and will show you how to set a cookie that remembers what stylesheet the user last requested.