Okay. What’s that mean?
Unobtrusive Degradable Ajax Style Sheet Switcher!
Boy are you in for treat today ‘cause we’re gonna have a whole lotta Ajaxifida Unobtrucitosity CSS swappin’ Fun!
Okay are you really kidding? Nope. I’ve even impressed myself on this one. Unfortunately, I don’t have much time to tell you the ins and outs of what I actually did to get this to work. We’re talking JavaScript, CSS, PHP…Ajax. But don’t worry about that. I’ve always believed that a good A.P.I. is an invisible A.P.I… and this I felt I achieved. The only thing you need to know is how it works and what to do.
A Quick Introduction Anyway…
First of all, the idea is very simple. I wanted something just like what Paul Sowden put together in
Alternative Style: Working With Alternate Style Sheets from Alistapart Magazine EXCEPT a few minor (not-so-minor actually) differences which I’ve listed briefly below:
- Allow users to switch styles without JavaScript enabled (degradable)
- Preventing the F.O.U.C. before the window ‘load’ when getting preferred styles
- Keep the JavaScript entirely off our markup (no onclick’s or onload’s)
- Make it very very easy to implement (ok, Paul did that too)
What I did to achieve this was used server-side cookies instead of JavaScript cookies. Hence, PHP. However this isn’t a “PHP style switcher” – which is where Ajax comes in. For the extreme technical folks, no, there is no xml involved here, or even a callback response. I only say Ajax because everyone knows what ‘it’ means. With that said, it’s the Ajax that sets the cookies ‘on the fly’. Got it? Awesome!
What you need
Luckily, I’ve done the work for you. It’s all packaged up in a nice zip file (at the end…keep reading for now) – so from here on out,
just follow these instructions
As I’ve mentioned, one of the things we’ll be working with is PHP. So, first things first, open up a file called index and save it with a ‘.php’ extension.
Next, place the following text at the top of your document (even above your DOCTYPE)
<?php
require_once('utils/style-switcher.php');
// style sheet path[, media, title, bool(set as alternate)]
$styleSheet = new AlternateStyles();
$styleSheet->add('css/global.css','screen,projection'); // [Global Styles]
$styleSheet->add('css/preferred.css','screen,projection','Wog Standard'); // [Preferred Styles]
$styleSheet->add('css/alternate.css','screen,projection','Tiny Fonts',true); // [Alternate Styles]
$styleSheet->add('css/alternate2.css','screen,projection','Big O Fonts',true); // // [Alternate Styles]
$styleSheet->getPreferredStyles();
?>
The way this works is REALLY EASY. Pay attention closely.
Notice in the first line we’ve included our style-switcher.php file.
Next we instantiate a PHP class called AlternateStyles() which will allow us to configure our style sheets.
So for kicks, let’s just call our object $styleSheet
As part of the AlternateStyles object, there lies a public method called add. So naturally with our $styleSheet object, we can call it to (da – da-da-da!) Add Style Sheets!
How the add() method works
The add method takes in a possible four arguments, only one is required. However, you’ll want to add some… since the whole point is working with alternate style sheets.
$path can simply be a uri, absolute, or relative path to your style sheet. $media adds a media attribute to your style sheets. $title gives a name to your style sheets (via title attribute).$alternate (which shows boolean) simply tells us that these are the alternate style sheets.
add() Tips
For all global style sheets (meaning the ones that will always be seen and will not be swapped out), simply use the add method as shown next to // [Global Styles].
To add preferred styles, do the same, but add a ‘title’.
To add the alternate styles, do the same as what we’ve done to add preferred styles, but add the extra boolean and set it to true.
Note following when adding style sheets
- Multiple global style sheets are allowed
- You can only have one preferred style sheet (That’s a browser rule)
- Feel free to add as many alternate style sheets as you like
Moving on
Simply add the following snippet to the <head> of your web document:
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript" src="js/alternateStyles.js"></script>
<?php
$styleSheet->drop();
?>
Nothing much to explain here. Just use your copy & paste powers.
How to Switch Styles
Whether you knew it or not, this baby already has the built in ‘ubobtrusive’ functionality that lets you switch styles by the drop of any link with a class name of ‘altCss‘. Just drop them where ever you like in your document as follows:
<a class="altCss" href="index.php?css=Bog_Standard">Bog Standard</a>
<a class="altCss" href="index.php?css=Really_Small_Fonts">Small Fonts</a>
<a class="altCss" href="index.php?css=Large_Fonts">Large Fonts</a>
Take special note where the file is linking to. Yep. Just linking right back to the page we’re on. The only extra parameters we pass in is a variable called ‘css’ – and within that we append the names of our style sheets.
Also take very special note on the names of the style sheets have an under_score to take place of any spaces we might have.
Go ahead… play around and change the style sheet on the example page. Try disabling JavaScript and refreshing your browser. Still works!
Cool eh?
Well, I put this together in one night so it’s still a work in progress and very beta. If you’d like to hear more about it and its future development, be sure stop on by my site where I’ll definitely be maintaining it.
Download the beta anyway
Well this wouldn’t be fun if there was nothing to download. So we’re hooking you up so you don’t go home (or logoff) unhappy
Merry Christmas!
Thanks for listening and I hope U.D.A.S.S.S. has been well worth your time and will bring many years of Ajaxy Style Switchin’ Fun!
Many Blessings, Merry Christmas and have a great new year!
About the author
Dustin Diaz currently works for Yahoo! as a developer & programmer. Particularly he works within the SmallBusiness unit. He does his best to roll out all their services using web standards and innovation (along with, of course, imagination). He maintains a personal website at dustindiaz.com.

Comments
18/12/2005
Excellent tutorial! Thanks very much. I will be implementing this soon.
18/12/2005
Great way done… A more comprehensive way could have been reach here, or maybe easiest. Nevertheless it’s usefull and AJAX seems to have great way to prevent us from poorness and sillyness. Just say Whhoo? :-)
18/12/2005
Is there a working demo up anywhere?
18/12/2005
That was nice of you to include the link to the Beta but do you have any websites utilizing this we can all check it out?
18/12/2005
Guys – read the article! It links to an example page
18/12/2005
Nice, thanks Dustin. Glad 24Ways is back online too :)
18/12/2005
Thanks for the positive feedback so far guys.
And ditto what Drew said
There is a link in the article itself to the example :)
Thanks a ton for havin’ me too Drew ;) You rock!
18/12/2005
PC IE 6.0 – worked with javascript, disabled javascript and worked again, re-enabled javascript and it does not work.
18/12/2005
Jon,
Did you refresh the page each time after disabling/enabling?
18/12/2005
Hi Dustin
Maybe this is a stupid question, but if it works without javascript why not leave the javascript out altogether? (OK I know that means it’s not AJAX anymore)
18/12/2005
This may be an obvious one, but if you include the stylesheet switcher throughout your site, it would be best to make the non-javascript links point to the active page. Instead of linking to index.php use $_SERVER[‘PHP_SELF’]
18/12/2005
@Andy,
That would entirely defeat the purpose of this. As we all know, The JavaScript version would be more robust and occur ‘on the fly’ not to mention that PHP style switchers have long been around for quite some time.
@Justin,
Yep. That would be most ideal and a smart thing to do. I’ll just leave it up to the developer to figure that out and implement it how they like. But yea, that’s definitely the right track.
18/12/2005
Dustin, I don’t think Andy likes AJAX.
18/12/2005
Oh..sorry, I must’ve missed the link the first time. See it now…
19/12/2005
I’ve got nothing against AJAX at all. I was just confused about how the style-switching worked and how you did the switching without the Javascript. Opened the demo page in Firefox with javascript off and it all became clearer.
19/12/2005
Changing style sheet is overrated. Keep it consistent!
19/12/2005
@Andy: Glad you understood :)
@Viktor: It is not in fact over-rated as it has proved itself useful for many reasons such as font-resizing, zoom-styling, and page-printing. I’m sure others can throw out many other great reasons as well.
20/12/2005
Great article Dustin! I might find a use for this.
20/12/2005
Nice short tutorial. I is an excellent idea. Great stuff!
20/12/2005
Superb! Thanks for sharing!! Ive been using the ALA switcher for a while and found it to be really good but your method just rocks. It seems to be pretty robust and degrades so well. Im working on a new design at the moment and it took me 10 – 20 mins to implement this switcher.
@Viktor: Yes, keeping a design / style consistent is really important for many reasons, but a style switcher isn’t just about switching style, colour or graphics, its a tool to help the user customise the website to their needs (wide, thin, high-contrast, text only), whilst allowing the designer/developer to maintain control over the layout, what is shown etc.
Thanks Dustin!
20/12/2005
@Paul: Lemme know where you decide to implement it. I’d eventually like to come check it out :)
@Heiko: Thanks man. I had this idea for weeks – I just finally got around to writing it :)
@Dave: This article was inspired by Paul’s ALA Style Switcher – So hopefully you’ll still be receiving the same benefits but more :)
21/12/2005
Cool idea and nice work, but how is this really AJAX when the page does a complete reload for each switch?
22/12/2005
Seems nice. Only thing I’ve noticed is that if a person’s user agent allows them to change to alternative styles manually then the cookie is not updated. To fix this you would need to figure out the what user agents categorize such an event (something I’ve never seen documented) and add an event handler for this event that would create an Ajax request that merely updates the cookie OR just set the cookie client side.
22/12/2005
I’ve been using this method by Noscope. Have to try this version also…
23/12/2005
@Coward: Read the article – coward ;)
@Brian: Interesting idea. I suppose the idea here is that the only people doing that would be the one’s purposely trying to mess it up. You should see to it that you’re making it clear to your users that you’re giving them the ability to update their style preferences via your own methods.
Otherwise, you’d probably have to figure out a way to set cookies based on if certain images getting load from the alternate styles…
@Vesa: that version is a PHP only version.
23/12/2005
@Dustin: You’re right, it is clear that that is what you’re attempting to do, I just see it as some users may actually use features in their browsers, and it isn’t our fault that they would like to do so. Sure there are some features we shouldn’t code for (for example, we shouldn’t assume that they are using Firefox and have an extension that will do something), but those are rare cases. As it stands, this is probably one of the niftiest style sheet switcher I’ve seen, so I love it.
That said, I am by no means an expert JavaScripter as I’ve only been toying around with it for a short time, but to me it looks like you are cancelling the click event before you test whether or not the browser has Ajax ability. Does this not run on any browser that can’t support Prototype (I haven’t looked into Prototype to thorougly yet), and it’s just chance that all browsers that are supported by Prototype must have Ajax?
Shouldn’t we be developing for users without JavaScript, then for users with JavaScript but not Ajax, and then Ajax versions? This hits the non-JavaScript users and the Ajax people, but does nothing for people with JavaScript but not Ajax. If the click event was not cancelled, then non-Ajax JavaScript enabled users would fall back to non-JavaScript version. Is that too sharp a fall to degrade them that much? Should it then fall into another branch of code that makes it similar to your average client side style sheet switcher? If that branch is present, isn’t Ajax overkill? This question holds true for every Ajax application. Is this one of those times?
I don’t really have an answer for that (and since it’s 4:52 AM as I write this, I don’t know if that answer would even make sense), but I think it gives us something to ponder.
27/12/2005
Brian,
That is by far probably a very small minority group of a people, thus tackling something very big with a lot more cost. But as Joe Clark would say, “access by nature is for the minority – and yes, it does cost money”
The only thing that comes to mind if you really want to have this degrade for folks with JavaScript enabled but no xmlHttpRequest support (or the ActiveX comparable) – do a quick object detection first before canceling the click event. There, problem solved :)
Otherwise, Prototype did the rest of the Ajax Development cross-browserness for us! It truly is quite the time saver.
Commenting is closed for this article.