jQuery Style Sheet (CSS) Switcher

I have been looking for a nifty style-switching script, and have found none. So here is the code for a checkbox-based style switcher. This uses jQuery.

The Javascript:

  1. /*ChangeStyle.js:
  2. * -by Skaman Sam Tyler – http://rbe.homeip.net
  3. *
  4. * This script uses checkboxes to add and remove stylesheets from the page.
  5. * It takes the value of the ‘rel’ attribute from the checkbox and creates a stylesheet link with it.
  6. * */
  7.  
  8. if ($) {    //check for jQuery
  9.  
  10.   //on document load, uncheck all checked boxes and add function handler for
  11.   $(document).ready( function() {
  12.     $(‘.styleToggle’).removeAttr("checked");    //uncheck all checked
  13.     $(‘.styleToggle’).click( function() {        //add handler for clicking
  14.       toggleStyle(this.getAttribute("rel"));
  15.       return true;
  16.     });
  17. });
  18.  
  19. //the toggling of the style. it takes a single parameter: the href of the stylesheet to toggle
  20. function toggleStyle(href) {
  21.  
  22.   //check for presence of link, if it exists, delete it, else, add it.
  23.   if($(‘link[href*='+href+']‘).size()!=0){
  24.     $(‘link[href*='+href+']‘).remove();
  25.   }else{
  26.     console.log("Adding: "+$(‘link[href*='+href+']‘));
  27.     $(‘head’).append(‘<link rel="stylesheet" href="’+href+‘" type="text/css" media="screen" />’);
  28.   }
  29. }
  30. }

The HTML file should include something like this:

  1. <form name="styleSwitchForm">
  2. <li><label><input type="checkbox" rel="/styles/red.css" class="styleToggle"/> Red Style</label></li>
  3. <li><label><input type="checkbox" rel="/styles/blue.css" class="styleToggle"/> Blue Style</label></li>
  4. <li><label><input type="checkbox" rel="/styles/green.css" class="styleToggle"/> Green Style</label></li>
  5. </ul>
  6. </form>
  7.  

Tags: , ,

3 Responses to “jQuery Style Sheet (CSS) Switcher”

  1. Thanks for this looks like it could come in very handy.

  2. Sam says:

    Hey…

    I don’t mean to change the topic, but where did you people figure out how to program in HTML?…

  3. sam says:

    I learned HTML and JavaScript in late 1996 by reading through simple examples and tweaking them to fit what I needed. There were no free/cheap WYSIWYG editors, so I had to be creative. The general consensus on IRC channels at the time was to go to a page that incorporated a neat feature I wanted to learn, then view the source and tinker with it until I got it to do what I wanted. With the popularity of open source and the plethora of applications available today, you can use this method to learn almost any programming language!

Leave a Reply