June 16, 2007

June 07 Meeting - 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.

These techniques can be done on the client with JavaScript or on the server with a sever-side technology like PHP. The code for this style switcher was used from a great article (.pdf) on A List Apart, written by Paul Swoden.

Basically how it works is 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. 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.