Picnic Website Code Tutorials

Javascript CSS Style Sheet Switcher Tutorial

View Demo

You have two ways to implement a style sheet switcher - JS or PHP. Simply put, JS is easy (relatively speaking), and PHP is not as easy. While looking around, I found that Dynamic Drive offered the easiest and best Style Sheet Switcher there was. The JS script remembers the users preference as you navigate from page to page, and for any length of time (in days) that you specify. So, doing what I do best, I'm going to make it even easier! This code is so simple, I think it explains itself better than I ever could. Here it is in it's most basic form. If your unclear about anything, just study the source code in the example above. It does not get any clearer than that!

DO THIS! Download and save styleswitch.js >> Create a default.css (if you havn't already) >> and a alternate.css >> and link to them in the head of your page (in this order). Done!

Head Section

<link href="default.css" rel="stylesheet" type="text/css">
<link href="alternate.css" rel="alternate stylesheet" type="text/css" title="alternate">
<script src="styleswitch.js" type="text/javascript"></script>


<a href="javascript:chooseStyle('none', 60)">Default Style</a>
<a href="javascript:chooseStyle('alternate', 60)">Alternate Style</a>

... And a little explanation. Starting from the top! The defualt.css goes first, alternate.css goes second, and the styleswitch.js goes last. In the alternate.css the (rel="") attribute must read rel="alternate stylesheet", and must be given a (title="") of your choosing. Note: In your alternate.css, only specify the rules that are different from those in your default.css.

In the links which call the switch, the word alternate must match the title (e.g. title="alternate") in the alternate.css. The number 60 tells the styleswitch.js how many days to remember the last style clicked. That way user preference is honored the next time they visit your site. That's it!

Need help adding this or other code to your website? Post it here in the forum! Forum


Top Donators

Friends of Mine