Posts Tagged ‘style switcher’

jQuery Style Sheet (CSS) Switcher

Wednesday, April 1st, 2009

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.