A problem occured while loading the plugin: krl_flickr_photoset -> : Assigning the return value of new by reference is deprecated on line 18
kelvinluck.com: Switch stylesheets with jQuery
Get Firefox! creative commons

Switch stylesheets with jQuery

I’ve just discovered jQuery which is an awesome JavaScript library. From the horse’s mouth:

jQuery is a Javascript library that takes this motto to heart: Writing Javascript code should be fun. jQuery acheives this goal by taking common, repetitive, tasks, stripping out all the unnecessary markup, and leaving them short, smart and understandable.

As an example of how succinct and easy code written with jQuery can be I put together a little example that allows you to add a stylesheet switcher to your site. Check out the example in action.

The stylesheet switcher allows your visitors to choose which stylesheet they would like to view your site with. It uses cookies so that when they return to the site or visit a different page they still get their chosen stylesheet.

The JavaScript code that powers the example looks like this:

$(document).ready(function() {
                return false;
        var c = readCookie('style');
        if (c) switchStylestyle(c);

function switchStylestyle(styleName)
                this.disabled = true;
                if (this.getAttribute('title') == styleName) this.disabled = false;
        createCookie('style', styleName, 365);

Then all you need to do is to add a class of “styleswitch” to any links that you want to activate the stylesheet switcher and a “rel” attribute which corresponds to the “title” attribute of the link tag embedding the stylesheet you want to switch to. Just view the source of the example and all should become clear…

I’d appreciate any feedback on the effectiveness of this technique. I think it should work fine on any browser that jQuery supports (I’ve tested on IE5.5, IE6 and FF1.5 on XP and Safari on OSX). It should degrade gracefully by going to the href of the link when jQuery isn’t supported or JavaScript is disabled. I have linked to a page which suggests possible ways to deal with this situation (disable JavaScript and try and switch stylesheets on the example to see the page).

If you would like to use this code then please feel free to download the zip

  1. The example running perfect in IE.
    But it can not move to the correct position in Opera 9.
    How can I do? :(

    keel    Aug 14, 01:35    #
  2. Hi Keel,

    I’m not sure I understand what you mean by “move to the correct position” – can you elaborate? Are you talking about the stylesheet switcher?


    Kelvin Luck    Aug 14, 10:31    #
  3. Hi Kelvin, was using styleswitcher successfully on a test site with jquery, but using the jquery build from 01 July rev110, (to use interface and thickbox v2.0)styleswitcher no longer functions…..would you know,what has changed in later versions of jquery,that stops the styleswitcher from functioning ??????

    — Giuliano Marcangelo    Aug 18, 11:50    #
  4. Hi Giuliano,

    There was a bug in some versions of jquery where ‘link[@rel*=style]’ wasn’t working. I’ve just tested with the new rev 200 and updated the example and the problem seems to be fixed – is it an option for you to upgrade to that?

    If not simply change link[@rel*=style] to link[@rel=*style*] (ignore the bold, that is textile inserting formatting) which will make it work even in versions of jQuery with the bug (I prefer the former because it looks neater though!),


    Kelvin Luck    Aug 19, 13:54    #
  5. Kelvin,
    Many thanks, will update to rev 200 and test. Maybe that will also cure a problem,I have had with removeClass not working for me.
    Once again many thanks for sharing and taking the tie out to check

    — Giuliano Marcangelo    Aug 20, 11:43    #
  6. I would like to suggest a change to your styleswitcher, to add support for persistent stylesheets – which must be applied in addition to any alternate stylesheet. Persistent stylesheets have a rel attribute of ‘stylesheet’ and no title attribute and are supported by the best browsers.
    All you need to do is to add a condition ‘must have the title attribute’ to the jQuery expression used in the switchStylestyle function, by changing link[@rel*=style] to link[@rel*=”style”][@title] (note that I also had to add the quotes in the condition concerning the rel attribute for it to work properly).



    P.S. Any reason why you publish people’s email addresses? That’s how I finally got caught by spammers… (and also why I’m not submitting my true one – sorry for that).

    — Andrea    Aug 21, 17:00    #
  7. Hi Andrea,

    Thanks for the feedback!

    I had implemented persistant stylesheets in the version I am actually using but had forgotten to update this page – thanks for reminding me :)

    I found that for some releases of jQuery the rel*=style wasn’t working and I had changed it temporarily to rel=style (the bold word should be surrounded by asterisks – textile getting in the way again) but just now I found that the latest release of jQuery (r226 from subversion) is behaving as expected again.

    Sorry about publishing people’s email addesses – I didn’t know I was! It is just the default Text Pattern comments form. If you put in a web address and an email address it publishes just the web address, this is probably the best thing to do if you want to receive email updates when people respond to your comments. I can’t find a way to turn off display of email addresses so I think that’s the only solution – sorry,

    Thanks again for the feedback,

    Kelvin :)

    Kelvin Luck    Aug 24, 11:10    #
  8. Thanks for the script Kevin. As an arts graduate I have trouble understanding all this scripting business and this set of scripts does exactly what I want. Props.

    PS. I’m a bit of a newbie at this and it took me a bit of time to work out how to send the user back to where they came from, so I’ll show my referer PHP code here:

    if(isset($_COOKIE['style'])) { header('Location: '.$_SERVER['HTTP_REFERER']);
    Andy Leppard    Sep 1, 18:14    #
  9. Cool – thanks for that Andy. Just to clarify that you will only need that PHP for people who have JavaScript disabled,


    Kelvin :)

    Kelvin Luck    Sep 3, 10:35    #
  10. Hi Kevin,
    I only now came back and found your reply.
    Concerning textpattern and email address publication, as I haven’t got a web site of any plausible interest, I’m going to enter a fake url and my real email address.
    On the code, I have made another small change to one line, to autocorrect any possibile problem with trying to apply a style that doesn’t actually exist in the page. It happened to me a couple of times already, with embarassing effects, be it because I had renamed a style or because I was having different pages using different sets of styles (but sharing – by mistake – a cookie on the same path). I found the autocorrecting code to be the only way to fix the problem once it was stored in people’s cookies.
    To make sure I don’t end up with unstyled content, in the last line of the $(document).ready call I check for the presence of at least one link to the style returned by the cookie before calling the switchStylestyle function at all.

    if (c && $(‘link[@rel*=”style”][@title=”’ + c + ’”]’).size()>0) switchStylestyle( c );

    This way, if for any reason the cookie returns a style that is not referenced in the page, I’ll avoid disabling the default stylesheet.

    Note that you can be even more bullett-proof by performing this test at the beginning of the switchStylestyle function instead, like so:

    if ($(‘link[@rel*=”style”][@title=”’ + c + ’”]’).size()==0) return;

    That way, you’ll also autocorrect any possible error in the rel attribute of the link used to trigger the style switcher.

    This is a rather optional change, but I found it quite useful in my own projects.

    Cheers again,


    Andrea    Sep 10, 12:51    #
  11. Oops,
    in the previous message, second suggested change, the test must be on the ‘styleName’ parameter (not an undefined ‘c’ variable), of course.

    Andrea    Sep 10, 18:14    #
  12. Hi, to stop TXP from showing the email addresses, click on your “Admin” tab, then on the “Advanced Preferences” (yellow button) and make sure the choice “Never display email?” is set to yes (under the “Publish” heading).

    Nice bit of jQuery B.T.W.

    Brian McAllister    Sep 18, 14:49    #
  13. Great – thanks for the info Brian, TXP should never be displaying email addresses now (couldn’t find that setting hidden down there before!).

    And glad you like the style switcher!

    Kelvin Luck    Sep 18, 14:57    #
  14. Hey,
    Great script, thanks.
    I have one problem tough: i would like to use the alternate stylesheet as default, and have a link that would turn it off and leave only the plain style. Is this possible?
    Thank you

    Eduardo    Sep 20, 18:05    #
  15. Hi Kelvin (^_^)

    can’t say how much this cookie checking version of the switcher is usefull ! I was trying to check for the session.ID in PHP, but it seems lighter with cookies, I may try to target to a session.Id between pages if the browser actually don’t support js, but it looks like a bit of too much coding for just the effect :) if anyone…
    :) well i’m gonna see your zip for that but I think it’s well, simple and light, and if a browser don’t support jquery it won’t be a big deal, as soon everybody’s gonna know about jquery s superstar :D

    Thanx a lot

    Gooroo    Oct 5, 23:42    #
  16. Hi Kelvin,
    Awesome work on the style switcher! I decided to give it ago and 5 minutes later (if that), its up and works like a charm! The only thing i am a bit stumped on, is running it in thickbox. When doing so it says serverside script cant be found (or something that extent!). Is there something i am missing here? I know its possible, as i’ve seen it been done before, so i am sure its something i am missing :) I am using the latest version of jquery (not svn), thickbox and your style switcher – just not sure where the conflict is! Any suggestions would be much appreciated!

    — Chris    Nov 1, 00:37    #
  17. Hi Chris,
    Glad you like the styleswitcher…
    If I understand you correctly you are asking if you can have the buttons to switch styles inside a thickbox? The problem you are having doing this is that the relevant JS isn’t being added to those buttons (that happens on document ready). Try running this code once the thickbox is opened:

    return false;

    That should associate the links inside the thickbox with the relevant JS to switch the stylesheets…

    Hope this helps,

    Kelvin :)

    Kelvin Luck    Nov 1, 21:36    #
  18. Hi Kevin,

    do you know if it is possible to change a style sheet for an iframe ?

    thanks for your answer, and for your work !

    ublo    Dec 11, 15:19    #
  19. great switcher. is there a way to toggle between two style sheets? rather than having two links on the screen i am trying to have one that just toggles.

    — lucas charles    Apr 5, 17:31    #
  20. Hi Lucas,

    Yes, you can do this quite easily. Try something like this (untested):

    $(document).ready(function() {
    var stylesheet1 = ‘YOUR_FIRST_STYLESHEET_NAME’;
    var stylesheet2 = ‘YOUR_SECOND_STYLESHEET_NAME’;
    var c = readCookie(‘style’);
    if (c && c == stylesheet1) {
    c = stylesheet2;
    } else {
    c = stylesheet1;
    return false;

    Hope that helps,

    Kelvin :)

    Kelvin Luck    Apr 11, 09:36    #
  21. Hello I’ve used the your code to set up a switcher. When the site first load it doesn’t load a stylesheet.How ever when I select each of the switch links the sttlesheet change fine I’m not sure what I’ve done wrong as I followed you instructions completeley.

    — Nichola Paulette Rose    Apr 18, 14:32    #
  22. Hi Nichola,

    Do you have somewhere that we can look at your page? That would make it easier to figure out what’s going wrong…

    Do you have one stylesheet with rel=”stylesheet” and one with rel=”alternate stylesheet”?

    Do you have cookies enabled on your browser? Does my example work for you?

    Hope that helps,

    Kelvin :)

    Kelvin Luck    Apr 18, 15:10    #
  23. Kelvin (et al),

    Just wanted to say thanks for creating this, it’s saved me a whole load of headache! (Alas the client gave me plenty!)

    I had to modify the script to cover the site needs and thought I would share the solution with you all, and if anyone has any way better to do this then please let me know!

    1. Need to switch styles to enable font-sizes and padding to change for accessibility reasons.
    2. Need to switch colours and some backgrounds depending on what season it is, and/or via a link.

    1. Could not overwrite other styles when switching between objectives.
    2. Would still retain any persistent styles without further modifications.

    Setting classes to the stylesheet links and thereby allowing certain calls to ignore the other styles!

    $(document).ready(function() {
    return false;
    var c = readCookie(‘style’);
    if© switchStylestyle©;

    //have to create two cookies so I can get the correct data for the corresponding styles!
    return false;
    var k = readCookie(‘season’);
    if (k) switchSeason(k);


    function switchStylestyle(styleName){
    //If the link is NOT a season style then disable and re-enable
    this.disabled = true;
    if (this.getAttribute(‘title’) styleName) this.disabled = false;
    createCookie('style', styleName, 365);

    function switchSeason(seasonName){
    //If the link is NOT a typography style then disable and re-enable
    this.disabled = true;
    if (this.getAttribute('title') seasonName) this.disabled = false;
    createCookie(‘season’, seasonName, 365);

    Hope this helps anyone else in a similar situation!


    — Jon    Jun 18, 17:17    #
  24. I’m looking for something similar to this. What I’d like is for an alternate css style to be loaded dependant on the page they come from. ANy help would be appreciated.

    — ken    Aug 20, 21:53    #
  25. Hi there,

    When i visit my webpage for the first time no stylesheet is selected. How can i define a default stylesheet who is selected when i visit the website for the first time?

    thanks in advance,


    koen    Nov 7, 20:03    #
  26. Hi Koen,

    Like on my example page, you need one stylesheet with:


    and the others have:

    rel=”alternate stylesheet”

    The one which doesn’t have alternate in the rel will be the default stylesheet which is selected when the website is first visited.

    Hope that helps,

    Kelvin :)

    Kelvin Luck    Nov 8, 11:18    #
  27. muchas gracias, gran trabajo

    ctraos    Dec 4, 14:21    #
  28. hi kelvin,

    i have the same sort of problem other users mentioned above: when i visit the page for the first time there is no stylesheet selected.

    the default stylesheet has a rel=”stylesheet”, and the other have rel=”alternate stylesheet”. so that shouldn’t be the problem. tested that behaviour in different browsers.

    and here’s another brief question: how can i call one of the stylesheets with some sort of a referrer. say i want to start the webpage (that has the styleswitcher included) from another page, i.e. a link that says “View the page with Style XXX”. The style XXX will than be set to default.

    thanks in advance

    — timex    Dec 4, 20:24    #
  29. Hi Kelvin, Fantastic Switcher, however just one question re the switcher links. In the HTML you have href="serversideSwitch.html?style=style1"

    What is the significance of href="?style=style1". Can they be left out or must the ? stay for example…..excuse my asking this question however a response would be appreciated.Thanks,

    — Noel    Dec 10, 17:23    #
  30. Hi,

    @timex – weird about having no stylesheet when you first visit the page. Does the same happen on my example page?

    Re. calling with a referrer – you could change the line:

    var c = readCookie(‘style’);

    To something like:

    var c = document.location.search.substring(1);

    (untested but should mean that the value of c is whatever is after the ? in your URL). Obviously you could extend this to split find “style=” in document.location.search and extract the string after the equals…

    Hope that helps,

    Kelvin :)

    Kelvin Luck    Dec 10, 18:47    #
  31. Hi Noel,

    Glad you like it :)

    The “serversideSwitch.html?style=style1” in the links is there because we are doing progressive enhancement. If Javascript is disabled then the user is instead directed to a page.

    The idea is that on this page you would have a serverside script which would set a cookie to the value of the style passed to it and then when any page on your site is generated it would use this cookie to decide on which stylesheet to make the default. You would have to write this script yourself as it’s dependant on how the rest of the site is put together.

    Alternatively you could just put the link pointing to a HTML page saying something like “Sorry – your browser doesn’t support the javascript necessary to use our stylesheet switcher”. Only a very small minority of people should ever see this message anyway…

    Hope that helps,

    Kelvin :)

    Kelvin Luck    Dec 10, 18:54    #
  32. Hi Kevin,

    Firstly thank you for your reply last December. I am having a slight problem though with IE (theres a shock). When using Microsoft’s proprietary conditional comments the switcher no longer works. Just wondering if you or anybody else has experienced the same thing or is there any obvious workaround.



    — Noel    Feb 27, 00:00    #
  33. Hi Kelvin,

    Problem solved. I suppose looking back it wasn’t a problem in the first place. Simply use


    for IE only stylesheets within proprietary conditional comments and the switcher still works



    — Noel    Feb 29, 11:39    #
  34. Thanks for the style switch script, Kelvin. I made a sleight addition to your code that works wonders for me, and may help others… Normally when the style is switched with your script, any js generated page text disappears – which is expected since the page is not actually reloading. I assigned all js related text a class (.js_text, which is set to display:none in the css). I added $(”.js_text”).show(); to the first line of your script. Now all js text on the page is displayed when the style is switched. Check my site for an example. Rock on!

    Matthew Stolley    Mar 13, 21:59    #
  35. Hi Kelvin,

    thanks for the great script. My implementation however didn’t work out and i still can’t figure out why.

    Plesae have a look at http://www.cialog.com

    The styleswitch is in the page footer “day” and “night”

    It works lika a charm in safari and firefox but IE has no style when you try to switch from night (default) to day.

    any hint … would be much appreciated.

    ciao stefan

    — stefan    Apr 8, 09:15    #
  36. nice trick
    i used to use php , but i now i have switched to jquery

    — sumit    Apr 9, 15:51    #
  37. Hi Stefan,

    I guess it might be to do with your conditional comments for the IE specific stylesheet. If you remove this does it start to work?


    Kelvin :)

    Kelvin Luck    Apr 9, 22:21    #
  38. Hi ;)
    I’m relatively new to jQuery – just trying to learn it now… so this might not be a hard one for all you experts out there – but I’m stuck…

    I’ve implemented the CSS Switch successfully – thanks for sharing, Kelvin :) – but now I’d like to hide the switcher links when JS is disabled.

    I tried hiding it via CSS – then showing it via the


    command – which works fine. But then, of course, switching CSS will hide the links with the new CSS…

    I tried altering the your code, Kelvin – but without success… :(

    I’d appreciate it if anyone could help me with this….(I’m collecting my tests on this page)

    prisca    Apr 10, 18:13    #
  39. Hi,

    There are two ways you could deal with this problem. Easiest is probably to re-show the links after switching stylesheets. Put your $(”#switch”).show() just before the “return false;” in css_switch.js.

    Hope that helps,

    Kelvin :)

    Kelvin Luck    Apr 11, 17:20    #
  40. Kelvin ;)

    thanks so much for getting back to me on this – much appreciated :)

    I’ve edited my code as you suggested – but when I take out the $(”#switch”).show(); from the HTML and add in into the css_switch.js file – the links do not show up at all :’( Will keep trying…

    as you mentioned there would be 2 ways to solve this – would you mind telling how else I could try to get this to work?

    Thanks again :)

    prisca    Apr 12, 13:06    #
  41. Hi,

    Try leaving the code in both places. The first to show the links when the page loads and the second to re-show them after applying new CSS…

    The other alternative is to put a style=”display:none” directly on the span and show it through JS. Then loading a new stylesheet won’t re-hide it…

    Hope that helps,

    Kelvin :)

    Kelvin Luck    Apr 15, 20:56    #
  42. This is a great solution! I did have one caveat, however. My site uses lots of styles—we have site themes—so this solution wasn’t optimal since using alternate stylesheets took a while to load.

    To fix this, I replaced these lines:

    $(‘link[@rel*=style][@title]’).each(function(i) { this.disabled = true; if (this.getAttribute(‘title’) == styleName) this.disabled = false; });

    with this:


    This looks for an element named “link” with an attribute “title” that contains “theme”. It changes the attribute “href” of the link element to ”[styleName].css”.

    — Kal    May 26, 22:52    #
  43. Hi Kal,

    Thanks for the alternative implementation. I can’t tell for sure by looking at your code snippet but does your system also allow browsers to use their built in style switching ability (View > Page Style in Firefox)?


    Kelvin :)

    Kelvin Luck    May 27, 10:35    #
  44. No, it doesn’t, since I don’t include the actual CSS files on the page.

    — Kal    May 30, 04:07    #
  45. Hi Kelvin,

    Nice little script. I tested it out on a WordPress theme I’ve been working on, though have since removed it. I would like to use it eventually though, once I redesign my site.

    The problem I ran into was “flashing” of the default style. Switching to the alternate style worked fine, but if I say… refreshed or clicked to go to another page, I would see a flash of the default style before showing the alternative style properly.

    Any idea of why this would be?

    Nyssa    Jun 13, 04:56    #
  46. This works great. I’ve reformatted the code into a jQuery plugin style, and added a revert method to remove the cookie and go back to the default stylesheet.

    Additionally, I’m using the jQuery Cookie plugin to handle the cookies.


    e.styleswitch = function()
    return false;



    $(‘link[@rel*=style][@title]’).each(function(i) {
    this.disabled = true; }); e.cookie(‘styleswitch’, null, {expires: 365});
    return false; }); var c = e.cookie(‘styleswitch’); if (c != null) e.styleswitch.change©;


    e.styleswitch.change = function(styleName)

    $(‘link[@rel*=style][@title]’).each(function(i) {
    this.disabled = true;
    if (this.getAttribute(‘title’) == styleName) this.disabled = false; }); e.cookie(‘styleswitch’, styleName, {expires: 365});



    To revert to default style you simply need a link like:
    Revert style

    — dougal2    Jun 22, 14:28    #
  47. I have seen a cross browser PHP style switching code at http://www.nightingalei.derby.sch.uk

    Seems to work pretty good. Reckon it must set a cookie as when you go back to hte site after leaving it remembers which style you last chose. Obviously this will work even if the user has JScript turned off!

    — Jonny Briggs    Jul 12, 09:34    #
  48. This is nice but I also have the problem that #45 – Nyssa – has.

    The default style will flicker before the selected one is shown when I navigate to other pages.

    — Bjorn    Jul 14, 21:32    #
  49. Is there a way to display some sort of animation like a loading gif when they choose a new style?


    — joel    Jul 15, 01:55    #
  50. Hi guys,

    @Bjorn & Nyssa… I hadn’t seen this problem before and I wonder if it is to do with recent changes to the jquery document ready code. I know I saw a thread on the jquery dev mailing list about how that functionality has changed recently… Maybe document.ready is firing later than it used to and that is causing the flash?

    @joel – maybe you could show the loading gif on click and add an event listener to find out when the stylesheet loaded and then hide the gif… I haven’t tried it though and am on the road at the moment so won’t be able to… Let me know if you get it to work…

    Hope that helps,

    Kelvin :)

    Kelvin Luck    Jul 19, 02:31    #
  51. bjorn and nyssa – try setting your media attrib to “screen” i think this fixed the flicker for me.

    — taber    Aug 9, 07:44    #
  52. Kelvin.
    Being very new to web design. I have a problem applying the style sheet switcher. only the first index page retains the selected css style and switches. The other pages with the switcher in the head of the page have no css. What am I doing wrong

    Steve    Aug 16, 20:20    #
  53. Is there any way to switch stylesheets declared by < ?xml-stylesheet… instead of < link… element?
    Generally, is jQ able to access any of xml declarations (these before < !DOCTYPE ?)

    — zieliq    Sep 2, 21:41    #
  54. Unfortunately, this approach means downloading all the alternate stylesheets even if they are never used. For performance-conscious sites with many skins, this is an issue.

    The best cross-browser approach I’ve found so far for theme switching is to AJAX in styles and swap out the old CSS once they are completely downloaded and save the cookie for the next load of the page.

    Dave Artz    Sep 7, 21:35    #
  55. Question: I love the plugin, but I find in FF2 and 3, when I reload a new stylesheet, I need to force a refresh of the whole page to clear out the old stylesheet. It works in IE8,7, and 6… which blows my mind btw.

    How would I force a refresh when the style sheet changes in jQuery? Thanks, I am a little new to jQuery

    Matthew    Sep 14, 19:31    #
  56. thanks
    this is a very good plugin. but here a problem. I think this plugin can’t work whit ie7-js code.
    can you help me?

    — sajjad.eb    Sep 26, 20:48    #
  57. Thanks for the code. It works fine for what I need it, however I would like to have a splash page that gives the end-user a link choice of one style or another. Is this possible to do? Mind you the splash page will only serve as a portal to one style or another, and will not be seen after entering the site.

    — Ced    Sep 28, 23:23    #
  58. this is a very good plugin. greets from turkey


    neteyaz    Oct 3, 15:50    #