kelvinluck.com

a stroke of luck

jQuery styleswitch – now with toggle!

About three years ago I posted my stylesheet switcher switcher here. It was the first bit of programming I ever did using jQuery. Surprisingly enough it is still one of the most popular posts on my blog and I still get quite frequent questions about it.

One of the most popular questions is “how can you make the styleswitcher toggle between available stylesheets?”. So I just put together a little example of how to do this. While doing it I noticed that the original code wasn’t really that extensible which is probably why people were always asking that question! So I ended up rewriting the code a bit as well as putting together the new example. You can find it all here.

46 Comments, Comment or Ping

  1. This is very nice. I will try to implement this into a new website of mine.
    Nice work Kelvin. :)

    July 31st, 2009

  2. Very cool. But is it me or the readCookie part is missing?

    August 4th, 2009

  3. Hi Patrick,

    The read cookie stuff is included in the js file ( http://www.kelvinluck.com/assets/jquery/styleswitch/stylesheetToggle.js ) but not in the inline code of the page... Sorry for any confusion,

    Kelvin :)

    August 4th, 2009

  4. this is great! thanks for all the hard work!!! is there a way to make it go previous?

    August 4th, 2009

  5. Hi Mike,

    Currently the $.stylesheetToggle function will loop through all available stylesheets in order. If you want some other logic then you can use the $.stylesheetSwitch function to implement that logic. There are examples of both on the demo page. Does that make sense?

    Cheers,

    Kelvin :)

    August 4th, 2009

  6. sorry for being a noob, i really don't know how to make that previous function. :/

    August 5th, 2009

  7. Hey everyone, just wanted to point out that if you're using this in a website where a variety of stylesheets could be dynamically loaded (such as in wordpress, where plugins might add their own) you might run into a conflict.

    I fixed this very issue on my website by adjusting the jquery select as such:

    $('link[title*=stylesheet_toggle_option]').each(

    "stylesheet_toggle_option" is part of a phrase within the title attribute of my style include:

    <link rel="alternate stylesheet" type="text/css" title="Light Indigo theme stylesheet_toggle_option" media="screen" href="/assets/css/light/light.css" disabled="" />

    Just a heads up, and thanks for the jQuery plugin Kelvin!

    cheers!

    August 21st, 2009

  8. kaigou

    you TOTALLY saved me with this one. I'd been fighting with various show/hide jscripts (not being a js person, but a php person), and every single one demanded that I do a separate instance for its use -- and every time I tried to toggle them as a unit, the only scripts I could find/get-to-work would treat the toggle-button as a button... and submit the page! AUUGH. Finally I realized that if I could just TURN IT OFF, then that's all I want, and lo and behold, your script works beautifully for that. Now one button turns on all the help text on the page, the cookie remembers it, and if the user's familiar enough with the form to no longer need the help, it can GO AWAY. With a single click! Oh, joy. I think I'm gonna have a drink and celebrate, because you really did save my last few shreds of sanity. THANK YOU!

    August 25th, 2009

  9. Levi

    Hi Kelvin, I'm a little new to jQuery and I can't seem to get your style switcher to work. I've checked the source of your sample page, and I noticed that your toggle is linked to a "serversideSwitch.html". I've checked this post, the previous post and all the comments, as well as the codes for every single resource linked to both sample sites (the new one and the old one) and have found no reference to a serversideSwitch.html. Or any instruction on what to put on the href field of the toggle link, for that matter.

    This is all very confusing and I'd really appreciate it if you could find the time to help me out.

    August 29th, 2009

  10. Hi Levi,

    The purpose of serversideSwitch is to provide stylesheet switching functionality for users with Javascript disabled. You can see the file here:

    http://www.kelvinluck.com/assets/jquery/styleswitch/serversideSwitch.html

    You can see on that page what the requirements are for the serverside switcher but as I mention, it is only a small minority of users who will ever need this page. The styleswitcher should work fine for you without it (presuming you have JS enabled).

    Hope that helps,

    Kelvin :)

    September 1st, 2009

  11. Hey, this is great can't wait to see it in action on my site. Thanks for your work and talent.

    September 14th, 2009

  12. Very handy little script. I'll be putting this to use to show a broad range of styling capabilities in a demo for a product. This saved me some hassle and the code looks quite tidy. Thanks again.

    September 15th, 2009

  13. If you are using this with the latest jQuery the styleswitcher.js you may need to remove the @ in the [@*=style] areas as this support has been discontinued.

    Thanks for the code though it works really nicely.

    September 23rd, 2009

  14. Bob Block

    How should this script be modified so that it will _import_ another stylesheet and overwrite the active one partially, rather than replacing it completely?

    Thank you for the code and more power to you.

    September 27th, 2009

  15. Franck

    Do your Style Switcher manage sIFR titles ?

    I would like my style switcher to change the color of sIFR titles.

    October 1st, 2009

  16. Awesome switcher, ive just put it into my WP blog but im having trouble when making it change the color of my h1, h2, h3 and h4. I am using Cufon, but the color is styled with CSS but I cant seem to make it change depending on what style sheet your on...

    any ideas?

    October 1st, 2009

  17. jamie

    Hi Kevin,

    Nice job, seamless integration all working very well!

    One question... is there any way of adding a named anchor to the style switch? Reason being, I'd like to be able to move the page at teh same time as clicking the styleswitch...

    Just adding ?style=blue#anchor or #anchor?style=blue obviously won't work because of the over riding JS.

    Any ideas greatly appreciated :)

    October 8th, 2009

  18. Hi,

    @Ben - thanks for the headsup - I've fixed it now. I had previously fixed it but it looks like those @'s somehow reappeared!

    @Bob - I'm afraid not, this code is designed to complement the browser's built in "alternate stylesheet" functionality so it behaves in the same way.

    @Frank & Kevin - I'm sure that you can make the style switcher change cufon and/ or sFIR but you will probably need to add code to reinitialise the image swap after the stylesheets have changed.

    @Jamie - you will need to edit your code so that it doesn't just "return false;" in your click handler. You could either set location.href = 'nameOfTheAnchor' or you could just not return false and let the link go to it's natural destination (note that with JS disabled then there will be no way for the styleswitch to work then).

    Hope that helps,

    Kelvin :)

    October 12th, 2009

  19. Matc

    Great bit of code just what I was looking for, is there anyway of swapping the text link on the switch link though, i.e. instead of toggle it would display 2 sets of text links depending on what css file is being used, im trying to toggle between Normal and Hi Contrast at the moment

    THanks

    November 12th, 2009

  20. Nice work. I am having a strange problem that manifests in FF3.5 I am using small-caps with the pseudo-element "first-line'. I see a space after any losing tag that begins in the first line and extends to the second--unless I comment out $.stylesheetInit();.or remove font-variant.

    Why would your script interact this way?

    November 23rd, 2009

  21. Hi,

    That's really strange Dan - I can't think why that would happen... Do you have a URL to the page in question?

    Cheers,

    Kelvin :)

    November 29th, 2009

  22. http://www.sorenkierkegaard.org/philosophical-fragments.html

    Notice the second line has a gap at the end of the word "Postscript". Hover over the link and the gap disappears. Comment out $.stylesheetInit(); and the problem goes away. But it's not just links. It's any tag that starts in the first row and closes in the next. This did not happen with an older version of your script. Also, on some of my pages--even without a link in the first paragraph, the dropcap shifts suddenly.

    Also, in Safari 3 for Mac, the dropcaps become HUGE.

    November 30th, 2009

  23. Kim

    Thank you for this script!

    Works perfect for me (-:

    December 2nd, 2009

  24. hey, just wanna say, i'm using it on my site now. check it out: http://www.mikemai.net

    thanks so much for making this!!!

    February 1st, 2010

  25. Anders

    I have a couple of css files like this

    main.css
    menu.css
    forms.css

    I want to make it possible to change the background image. So the simplest solution that comes to mind is to have the css for "body background image" in a couple of separate css files

    background1.css
    background2.css
    background3.css
    ...

    Then load the appropriate css file and leave everything else as is. Is this what this plugin is intended for (or is it even possible)?

    March 28th, 2010

  26. ^^

    that's exactly how i organize my css too. just changing the body background. but on my other site, i change the text and link colors as well: http://helveticasux.com

    March 29th, 2010

  27. Anders

    Thanks Mike for confirming. I'll have a go at it now.

    March 29th, 2010

  28. if it helps, you can view source on my site: http://www.mikemai.net/

    i also set up a php function to change background automatically every hour. fun stuff. :)

    March 29th, 2010

  29. Anders

    Works like a charm. Thanks Mike!

    March 29th, 2010

  30. rebecca

    hi, kelvin.

    thanks for this beautiful plugin.

    but now i need to indicate currently active stylesheets, and it would be better in a drop down menu. once i choose an option, this option will active a stylesheet as current style. i have no idea how. can you give a hint? thanks.

    April 5th, 2010

  31. @rebecca

    since this doesn't reload the page, i think you can just make a dropdown list with each option linking to a switch. whatever you click on should stay i believe. i haven't tried it so i might be wrong

    April 5th, 2010

  32. Rebecca

    thx, mike.

    i just find out in this sample, kelvin gives a way aready to solve this problem by using css. thank u all.

    April 6th, 2010

  33. chad

    Hey.

    This is exactly what I was looking for (thanks a ton!). The only glitch I noticed is that the page seems to load the original style sheet and then a split second later (after much of the content is on the page), it then loads in the alternate style sheet. Is there a way to make this more seamless. I don't work with jQuery and was doing some research. Apparently this will do it: $(document).ready(function(){ but I'm not sure how where to implement that (as per: http://15daysofjquery.com/quicker/4/ )
    Can anyone help??

    April 6th, 2010

  34. Finally i came with this

    Source here : http://plugins.jquery.com/project/AddOrSwitchStylesheet
    Use cookie manager from : http://plugins.jquery.com/project/cookie

    (function($){

    // Stylesheet management... by molokoloco 2010
    // Source here : http://plugins.jquery.com/project/AddOrSwitchStylesheet
    $.fn.extend({
    styleDisable: function(disabled) {
    setTimeout(function() {
    $(disabled).each(function() { $(this).attr('disabled', 'disabled'); });
    }, 250);
    },
    styleSwitch: function(stylePath) {
    var exist = false;
    var disabled = [];
    // No modification for other styles -who can be on the page- without id attribute
    $('link[@rel*=style][id]').each(function() {
    if (stylePath == $(this).attr('href')) {
    $(this).removeAttr('disabled');
    exist = true;
    }
    else disabled.push(this);
    });
    if (exist == false) $('head').append('');
    $.fn.styleDisable(disabled);
    $.cookie('css', stylePath, {expires:365, path:'/'});
    },
    styleInit: function(linksWithRel) {
    if ($.cookie('css')) {
    var isSet = false;
    $('link[rel*=style][id]').each(function() {
    if ($.cookie('css') == $(this).attr('href')) isSet = true;
    });
    if (isSet == false) $.fn.styleSwitch($.cookie('css'));
    }
    $(linksWithRel).click(function(event) {
    event.preventDefault();
    $.fn.styleSwitch($(this).attr('rel'));
    $(this).blur();
    });
    }
    });
    $.fn.styleInit('a.css');

    })(jQuery);

    April 10th, 2010

  35. I love this script!

    ..... but I really need to find a way to be able to use the import rule so that my regular stylesheet loads, and the alternate stylesheet loads when called upon.

    Is this even possible? If so it would be a great improvemnt so that you can remove the vast amount of rel="alternate stylsheet" headers and just have the one stylesheet in the header.

    Thanks for the cool script though. Works like a charm!

    April 10th, 2010

  36. rebecca

    molokoloco, i visit your website, and test the switcher. same problem with Chad. the page load theme after a split second later, during loading , the page appear with no style. this is not perfect.

    April 14th, 2010

  37. Hi Rebecca,

    I have updated some bit of code here ( http://code.google.com/p/molokoloco-coding-project/wiki/MyJQueryPlugins )

    I have an explanation why my style switch slowly... My page is named "Fast web Start" i want her to load in less than 2 seconds, for so, i embed my picture with base74encode in my stylesheet.... so it's a little heavy, but with less connections call to server....
    I suppose for a normal CSS that work fine....
    Also you can play with the default delay of 250 ms, adjusting it to your style weight...

    It's never perfect ;)

    April 15th, 2010

  38. How would you integrate a loading animation?

    April 26th, 2010

  39. To animate CSS you would use
    http://api.jquery.com/animate/

    $('#book').animate({
    opacity: 0.25,
    left: '+=50',
    height: 'toggle'
    }, 5000, function() {
    // Animation complete.
    }
    );

    ;)

    April 26th, 2010

  40. Hello!
    I couldn't integrate it to my wordpress template.
    I can make it alert from clicking the link, but couldn't make it switch. Nothing happens.

    Tried the solution that Kurt gave above, but i think i couldn't make it right. Please someone help :(

    April 27th, 2010

  41. JoWannes

    Thanx for this script.
    I want to use this script on my website, but... when I add this one, I can't use other scripts (like imageviewers), because, once I include another css file, the stylesheet switcher don't work anymore...

    My code:

    Changed
    $('link[title*=style]').each(
    from stylesheetTogle.js into
    $('link[title*=mstyle]').each(
    (2x), and that works.

    Now, when I include

    It don't work anymore. :/

    How can I fix this?

    Thanx in advance!

    May 13th, 2010

  42. Jason

    Thank you for the amazing style switcher, but i do have one question for you. The cookie function doesn't seem to work in Google Chrome, but it does function fine in FireFox so i know the code is working. Is there a work around for Chrome? Thanks in advance.

    August 4th, 2010

  43. Hi,

    I was wondering is there is a way to use a form to change the style instead of links (as the Style Sheet Switcher from Dynamic Drive : http://www.dynamicdrive.com/dynamicindex9/stylesheetswitcher.htm)

    I have to admit that I made several tries but I'm not enough familiar with JS and jQuery to know exactly what to do.

    Thanks in advance for your answer

    See you

    August 13th, 2010

  44. Lis

    Hi there,

    Managed to get the switch working for a high-vis version of a site i'm working on. i've noticed a glitch though, as my main stylesheet has jquery animations on it (i think using a newer version of jquery) when i go into the high-vis version and view a different page then go back to the original stylesheet the animations don't work correctly.

    Any ideas?

    Thanks

    September 2nd, 2010

Reply to “jQuery styleswitch – now with toggle!”