Swap Style Sheets Instantly On The Fly

Being able to swap out stylesheets on the fly with javascript is both simple and useful. Practical applications would be

  • Changing the font size if the person clicks on a button because they’re visually impaired
  • If you have a theme for sale, on the preview screen you could display multiple color variations.

Check out a variation to this site



The code for this might seem a little head scratching at first, but the javascript is only 1 – 2 lines! First, we attach an “onClick” to the button, and inside the parenthasis, put the file path for the new style sheet. So it would look like this

<input type="button" value="Click Me!" onClick="theswap('/wp-content/uploads/style2.css')">

Just be a little careful with your file paths, and be sure its actually pointing to your style new style sheet. The easiest way to handle the javascript is to acutally go to your current stylesheet that you’ll be swappign out, and give it an ID, just like you would give to any other element. Then the javascript just calls the funcion (I named mine theswap) and changes the href to our new parameter.

<link id="mystyles" rel="stylesheet" type="text/css" href="includes/styles.css">
<script>
function theswap(newsheet){
document.getElementById('mystyles').setAttribute("href", newsheet);
}
</script>

So we grab the new file path from the button, and give it a variable name of “newsheet”, then use that to change the href of the stylesheet (with an ID=”mystyles”)

Have some cool style sheet swaps that you’ve made? Share the link below!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>