Solutions. For Life.

jQuery Style Sheet (CSS) Switcher

posted on: 4/1/2009, 6:16:00 PM

last updated: 4/1/2009, 6:16:00 PM

by: skamansam

Reading Time: less than a minute read

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:

* -by Skaman Sam Tyler -
* This script uses checkboxes to add and remove stylesheets from the page.
* It takes the value of the 'rel' attribute from the checkbox and creates a stylesheet link with it.
* */

if ($) {    //check for jQuery

  //on document load, uncheck all checked boxes and add function handler for
  $(document).ready( function() {
    $('.styleToggle').removeAttr("checked");    //uncheck all checked
    $('.styleToggle').click( function() {        //add handler for clicking
      return true;

//the toggling of the style. it takes a single parameter: the href of the stylesheet to toggle
function toggleStyle(href) {

  //check for presence of link, if it exists, delete it, else, add it.
    console.log("Adding: "+$('link[href*='+href+']'));
    $('head').append('<link rel="stylesheet" href="'+href+'" type="text/css" media="screen" />');

The HTML file should include something like this:

<form name="styleSwitchForm">
<li><label><input type="checkbox" rel="/styles/red.css" class="styleToggle"/> Red Style</label></li>
<li><label><input type="checkbox" rel="/styles/blue.css" class="styleToggle"/> Blue Style</label></li>
<li><label><input type="checkbox" rel="/styles/green.css" class="styleToggle"/> Green Style</label></li>