jStyler

The first time you write a plugin, however simple it is, a sense of accomplishment takes over. It might last a couple hours, but those hours are precious as walking on the moon. As a person who recently got addicted to jQuery, the library has certainly lived up to its reputation in helping cutting lines of codes. Without further ado, here’s my first jQuery plugin – a stylesheet switcher.

This is a cookie based style switcher. Once a stylesheet is selected, it will use that stylesheet until the cookie is removed. Also note that Javascript is case sensitive. Make sure that the title attribute for the <link> and the href has the same case.

View jStyler’s capabilities here.

Step 1: Link the script files

Link all the necessary Javascript files.

<script type="text/javascript" src="jquery-1.2.2.min.js></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="switcher.js"></script>

Step 2: Set up stylesheets

First, list out all the stylesheets you would like to include in your site. All except the default stylesheet gets an additional “alternate” attribute in the rel attribute. Add a title to each stylesheet. This will be the identifier for your stylesheet.

<link rel=”stylesheet” type=”text/css” href=”screen.css” title=”A” media=”screen” />
<link rel=”alternate stylesheet” type=”text/css” href=”screen2.css” title=”B” media=”screen” />
<link rel=”alternate stylesheet” type=”text/css” href=”screen3.css” title=”C” media=”screen” />

Step 3: Set up your style switcher

This is what will invoke the stylesheets. For the sake of presentation, I am using color blocks as my switcher. You can use any other forms of HTML elements to create the switcher.

The selected stylesheet will be indicated using a css class on appropriate a tag using a classname of “on”.

<ul id="switcher">
   <li><a href="#A"><img src="images/A.gif" alt="A" /></a></li>
   <li><a href="#B"><img src="images/B.gif" alt="B" /></a></li>
   <li><a href="#C"><img src="images/C.gif" alt="C" /></a></li>
</ul>

Step 4: Lastly, call the function

The last thing you need to do is call up the function. That is all.

<script type="text/javascript">
 jQuery(document).ready(function() {
   $('#switcher').switcher();
});
</script>

5. What if I have a stylesheet that always has to be active?

You might want to use a global css file that contains all repeating code and would like to not repeat it in each stylesheet. Well, don’t worry. All you would have to do is place the file or files on top before the switcher stylesheets and do not give it a title (this is important).

<link rel="stylesheet" type="text/css" href="reset.css"  media="screen" />
<link rel="stylesheet" type="text/css" href="screen.css" title="A" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="screen2.css" title="B" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="screen3.css" title="C" media="screen" />

Download sample code.

35 Responses to “jStyler”

  1. dimas on July 2nd, 2008 at 11:09 am

    What the point of use jQuery.

    it’s can be done like this:

    html:
    <a href=”getNewCSS(1); void(0);” rel=”nofollow”></a>

    JS:

    function getNewCSS(cssIndex) {
    var newStyleSheet;
    switch (cssIndex) {
    case 1:
    newStyleSheet=’go1.css’;
    break;
    case 2:
    newStyleSheet=’go2.css’;
    break;
    ……..

    default:
    newStyleSheet=’go0.css’;
    break;
    }
    document.getElementById(“myStyleSheet”).href=newStyleSheet;
    }

  2. Dhana on July 2nd, 2008 at 2:09 pm

    Dimas,
    You definitely could. But I would change the implementation to be non-obstrusive as it would make the code more readable and it will also degrade gracefully in browsers that don’t have Javascript enabled.

  3. Ruth on July 12th, 2008 at 12:13 pm

    Thanks for this example and the explanation of use. You seem to have a newish site, with few comments, yet, from what I have seen so far – you have some interesting stuff here. I’ll bookmark you and pop back again.

    Thanks

  4. Dhana on July 12th, 2008 at 4:50 pm

    Ruth,
    Thanks for visiting. Hope it was helpful to you.

  5. Ruth on August 6th, 2008 at 5:05 am

    Here might lie a “challenge”.

    Let us assume, we have a few stylesheets, and we create one page on a site, where the site user can go to “change the look” of the site – your JStyler stuff works great and does just that, right out the box.

    Currently, it appears that every other page on the site requires the links to all stylesheets and alternate stylesheets, for this to fully work.

    However, here is a thought. Is there anyway, that we can link to ONE style sheet on every page – let’s call it “chosen stylesheet”, or, if none selected – load the default stylesheet.

    Thus, when a user changes the “chosen stylesheet” using JStyler (on the specific JStyler page) – it modifies sitewide.

    Why? because we can then ADD additional stylsheets – over time, without having to modify the entire site…

    Or, can you already do this and I have missed something?

    Um, yes, I am still playing with your styler and having great fun to boot.

  6. Dhana on August 6th, 2008 at 6:06 pm

    Ruth,

    I think I get what you mean. This has never crossed my mind before as usually I use templates or reusable controls (include files) so that I can just keep one copy for easier maintenance. But looks like you have just pointed out a great addition I could be making for the jStyler. Looks like I will be spending some time implementing it.

  7. Ruth on August 7th, 2008 at 4:08 am

    I understand the notion of a “template”. I am also grasping the notion of using PHP includes etc. And, yes, I am well aware that there are stylesheet switchers created using PHP that call from one file. However, not everyone wants to use PHP etc to achieve this.

    With the interest in JStyler/JQuery and all its abilities, the notion of being able to add stylesheets at a later date, without modifying every page on a site, does, to me, seem like a terrific addition.

    Given that IE<7 has key “hiccups” one method of curing some of these issues, is by using a javascript stylesheet switcher – but, some of these clash with JQuery (i.e. if you use JQuery for other things – like a gallery).

    So, by implementing a stylesheet switcher that uses JQuery and that achieves a measure of ultimate usability in terms of adding more stylesheets at a later date and having this take effect site wide – yes, it would be a real good addition.

    I was not trying to get you to go through hoops or put in huge blocks of time here, I just wanted to offer a suggestion, so don’t feel compelled. I am sure you have a heap more things to think about. Currently, I am having to look to a PHP solution, which I am not thrilled about.

    You have to remember, I raise sheep on a croft and am not in any way a website developer – or whatever they are called.

  8. Ruth on August 10th, 2008 at 4:14 pm

    Further thoughts

    Well on with messing with PHP includes. All well and good, so far.

    Now, we move on to accessibility and that apparently oft misused “long description”. So, if, for every image on every website, we have to create an extra page to “provide that extra bit of description” – that does not seem to be 100% accessible. Just exactly how many people understand their “back button”.

    So, wouldn’t it be “novel” if a JQuery component were to be built that allowed, at the press of a specific key, a small online window to pop up (kind of like a tool tip I guess) – that displayed the relevant “long description” information…

    Well, that might not pass the W3C tests. But. It might, if all the information for every image on a website was contained on one htm page and, each “snippet” of info was then brought into the little opening window. Get my drift?

    Thoughts?

  9. Dhana on August 11th, 2008 at 8:51 pm

    Ruth,

    Looks like that question needs a longer answer that can fit here. Check out Progressive enhancements with “longdesc”

  10. ruth on September 8th, 2008 at 7:13 am

    One final question on JStyler – HOW does it know which is a “default” stylesheet, so, that when the site is first loaded – it loads with a style and not unstyled?

    I spent quite a while figuring out how to use JStyler with PHP includes, finally figured it out. Of course, I can’t really test this using XAMPP on my “local” machine – so I stuck it online.

    My test page loaded completely unstyled. When I scrolled down to find my stylesheet changer links and clicked one – up came the page again fully styled.

    I came to the conclusion I must have done something wrong here – but I can’t for the life of me see what – I followed carefully all the instructions above…

    So, question is – how does JStyler get to know which stylsheet should be loaded for a first time visitor???

  11. Dhana on September 8th, 2008 at 8:15 pm

    Ruth,

    The first stylesheet that should load by default should have HTML just like this without any alternate in its rel attribute.
    <link rel="stylesheet" type="text/css" href="screen.css" title="A" media="screen" />>

    If you have the page online, I can take a look at the HTML to see the implementation.

  12. ruth on September 9th, 2008 at 11:28 am

    there it is – all stylesheets listed, and, they appear to be correct… um, don’t they?

  13. Dhana on September 9th, 2008 at 9:30 pm

    Ruth,

    I have to say it was none of your fault in implementing it. I just realized that I never took into account users adding default stylesheets that will not be toggling when switching. So, I made some code changes and you can get the latest version here. Also updated the documentation.

  14. ruth on September 10th, 2008 at 4:01 am

    I’ll go download it now. Thanks for taking the time to work it out. I know it has been a while since I first downloaded the “plugin”, but it took me a while to figure out how to use includes, before I could test “live”. Had I known what I was doing, I might have been able to suggest there might be an issue earlier.

    This is some learning curve I am on. Thanks for all the help.

  15. Matthew on October 8th, 2008 at 11:26 am

    I love jswitcher, but I have a strange bug.

    If i have a site with different pages in different folders, it seems as though jswitcher sets a new cookie per folder.

    (example: most files are in the root – I set the stylesheet from A to B, then go to a page which is in the subfolder, “about” the stylesheet is set to A, not B. If I change the page in About to stylesheet C, and then go back to files in the root of the directory, they are still set to B)

    I would love help on this as I am trying to see how to fix this and it is beyond my little designer brain.

    Am I doing something wrong?

  16. Dhana on October 8th, 2008 at 4:24 pm

    Matthew,

    A fix has been uploaded so that sites with multiple folders will share the same cookie.

  17. Matthew on October 9th, 2008 at 5:34 am

    Dhana!

    My goodness you are fast! Thanks so much for fixing that / adding the additional functionality.

    Am I correct in understanding the value in line 36 path: ‘/’ is what looks at the root of the site to determine the cookie? That is so cool.

    Could you modify to a specific subfolder if the site was not at the root of the domain? so the value could be path:’/UBS’

    Thanks again you are awesome!

  18. dP on October 26th, 2008 at 4:57 am

    Hey would it be possible to make this script have different classes of css files, so users can customize different parts of the site to there liking.

    by my understanding this is the basic.

    persistent = main.css

    alternative =
    Blue.css
    orange.css

    what i would like to know is, is it possible to have a group of stylesheets to switch between in there own class.

    i.e

    persistent = main.css

    alternative =
    class = bodystyle
    Blue.css
    orange.css

    class = background-color
    grey.css
    white.css
    black.css

    will it be possible to do this with just this one script?

    I’m not a java script coder just a designer web page coder and would like to know what sort of options i can have.

    Regards,
    dP

  19. Dhana on October 26th, 2008 at 8:55 pm

    dP,

    Not sure if I am following you, but let me see if I got your question correctly. You’re saying you have different css files that hold different information(i.e headings go into a heading css class, background colors into another, etc). What you would like to do is when the selection is chosen, you would like to toggle to a different set of css files – basically toggling activates multiple css files instead of just one?

    If that’s the question, as of now, the script only supports the toggling of one stylesheet to another. But it looks like an addition that would be good to the script and I might just work on that.

  20. dP on October 27th, 2008 at 5:16 am

    its not toggling multiple css files at the same time. its allowing users to select combination of css files giving greater customization optoins.

    take this site that I’m developing. http://www.ani-haven.net/

    im going to create a black version as well and will be using ur script to allow users to switch between styles.

    white.css and black.css

    The site admin also wants to allow users to change background colors and the banner image as well to there liking.

    i was wondering if the banner style sheets could be made with just the div id for and info required to change the banner image,
    and when selected it will still keep either the white or black css file that the user has chosen for base color.

    you get what I’m going?

  21. Dhana on October 27th, 2008 at 9:45 pm

    dP,

    Allright, got it this time. It looks like the way you want it working is not how the jStyler is set up at this point. I can however suggest a simple little fix you could implement to achieve that. For example, to change the banner image, every time a banner selection is chosen(for example from a dropdown), you could do this:

    <img src="banner0.jpg" alt="" id="banner_image">
    <select id="banner">
    <option value="banner1">Banner 1</option>
    <option value="banner2">Banner 2</option>
    </select>
    $('#banner').change(function(){
    var selected = $(this).val();
    $('#banner_image).attr('src',selected + '.jpg');
    });

    The idea to change the background color also follows the same line of thought. See if this works for you.

  22. brad on November 20th, 2008 at 4:19 pm

    Can you add a default global style sheet to your example. I can’t seem to get it working, with just leaving the title attribute off.

  23. Progressive enhancements with “longdesc” « idhana.com on January 5th, 2009 at 10:50 pm

    [...] just received this comment today by Ruth and when I read it, I thought, yeah, why not. “longdesc” as the name says [...]

  24. Tim on January 26th, 2009 at 12:34 pm

    Hi…your script works great. One question…

    I have it set up to increase/decrease font size and when the page first loads you can see the font size increase(for a second) before the default style sheet kicks in with the smaller default text. Does that make sense? You see big text turn to small because of the lag.

    Is there any way to correct this?

    Thanks,
    Tim

  25. Dhana on January 26th, 2009 at 7:04 pm

    Tim,

    Do you have a url I can have a look at? I can see how this can be an issue, I can work on an extra feature that turns on a loading animation with an overlay which might solve this issue, but it might take a week to do this so I am little bogged down by work this week.

  26. GJ on January 27th, 2009 at 7:59 pm

    Hey,

    I can’t seem to get it working. The “default” stylesheet (the one with no alternate in the rel attribute) won’t load so when u visit the page for the first time you have no style. My link is http://www.omarietje.nl/cps

    Any idea what I’m doing wrong?

  27. Dhana on January 27th, 2009 at 9:04 pm

    GJ,

    Try putting the script tag where you declare the switcher at the end of the page. Looks like what is happening is the Javascript is being executed before the element is on the page, hence it’s not setting the styles. If you move it to the end of the page or after the “switcher” div, it would find the div.

  28. ruth on March 25th, 2009 at 12:31 am

    As you know, I played around with JStyler when you first created it. Now, I am implementing it on an actual site.

    I have the whole site done. All the pages load with the default style sheet – EXCEPT the page that allows the actual switching to be done. This appears to be the same issue that GJ has had. The page loads with no stylesheet attached – it has not found the default.

    I moved the actual switcher javascript trigger around. It has been located at the foot of the page and under the actual calls. Neither worked.

    This morning, I tried switching the positions of the javascript calls in the header – so they came AFTER the stylesheet lists. That didn’t work either.

    Maybe there needs to be some if statement in the switcher trigger that appears on the page. ??

  29. Dewi on April 21st, 2009 at 5:42 am

    It didn’t work for me because the rel attribute in the link objects should be written with a capital letter:


    Don’t know if it is a problem for other people however…

  30. Dhana on April 21st, 2009 at 7:34 pm

    Dewi,

    Not sure what you mean here. Do you mean the title attribute in the href and the stylesheet href? Yes, those are case sensitive – you would have to make sure they have the same case for it to work.

  31. Sarah on July 21st, 2009 at 10:54 am

    This is a great one. Could you tell me how I can allow one to put in an URL to a tiled pattern into the input field, and have the background image be replaced upon submit or something?

    And also, any possible way to make the selected css via clicked link, styled so one would know which link is in use?

  32. Dhana on July 21st, 2009 at 6:05 pm

    Sarah,

    I think I need you to clarify the first question so I could understand it better.

    As for the second one, that’s easy. In the stylesheet, look for the line below. You can add any other specific styles to it to indicate it’s currently the selected on. For example, I am now making it have a black background.

    #switcher li a.on{
    border: 1px solid #cccccc;
    background: #000000;
    }

  33. Sarah on July 22nd, 2009 at 4:00 pm

    Thanks for the fast reply :)

    I wanted to include an input field box into a webpage and an user like me would put in an URL to an online hosted tiled pattern and then an input button to submit so the background image in the CSS can be replaced. Would that be doable?

  34. Grey on February 17th, 2010 at 4:38 am

    Hi there,
    I’ve noticed there is an issue here if you want to use conditional stylesheets in ie6 and 7 as they operate via the cascade – overwriting styles in the main stylesheets.
    i.e if you place them above all the stylesheets for switching, they are no longer any use

    Any ideas as to how we could place stylesheets below and still have them operate outside the switcher?

  35. Dhana on February 17th, 2010 at 10:31 pm

    Grey,

    Good catch. I can work a solution for that over the weekend – to update the plugin to accommodate such cases.

Leave a Reply




You may use the tags listed below in your comments:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Published in
Tagged under
Some other categories