Style Switcher with jQuery

Wednesday, April 7. 2010

While developing an Adobe AIR application using CSS/HTML/JS, I decided I wanted to allow for templating of the application. The default template has the ability to switch view states (horizontal, or vertical). Since I'm building the application with CSS, HTML and JavaScript (with jQuery), I thought that in order to create this effect, I'd use a style switcher.

I then thought...hey, I wonder if this would work in browsers other than the WebKit version I've been testing under?!

It worked in Firefox 3.6.3, Opera 10.51, Chrome 5.0.342.8 beta, and Internet Explorer 6 (although my test CSS was broken in IE6). Opera 10.50 (tested first) had an issue with loading the secondary CSS on first attempt, but had it cached after that. 10.51 loaded everything just fine, but I can't be sure if it was still cached from the attempt with 10.50, or if 10.51 fixed an unknown issue to help fix it.

So, how did I do it?

Back in the day, Firefox had a little-known and not-often-used feature that allowed web-designers to incorporate multiple CSS layouts/designs right in the site, and the users could choose on-the-fly which UI they'd like to use (on each session) by going to View, Page Style, and then choose the style you wanted - if more than a single style was available from within the code. To give users this option, you include secondary stylesheets after the first, but in the link element, you specify that it's an alternative stylesheet, as so:


I originally started with this concept and tried swapping out the primary for the secondary and vice versa. Unfortunately this had some issues during development that may have been related to some other problems, but I dropped this attempt (but if Opera has a problem with caching, this route would solve that). Instead, I simply changed the href property of the link element. It was easier to target with jQuery without using URL matching/REGEX, or arbitrary naming of the rel property.

Anyhow, here's the code that I used (in this example, I am clicking on a button with ID of "switch"):


What this is doing:
  • Bind an onClick event to the element with an id of "switch"
  • find the LINK element of a media type of screen that contains an href property and assign it to the variable "cssStyle"
  • fade out the application (or a website wrapper?)
  • swap the CSS style for another (inline), depending on what's currently loaded
  • fade the application (or website wrapper) back in with new style

...and we now have our style swapped out (quickly and easily) for an entirely new style.
(Page 1 of 1, totaling 1 entries)