jQuery style switcher

It's often the case that you want to provide more than one CSS stylesheet for your app or website. You can do this by including a style switching function in your app. Here's how to do it in jQuery.

The solution uses jStorage to store the user's preference between sessions, but you could use cookies instead.

Here is the jQuery:
$(document).ready(function () {
    var myStyle = $.jStorage.get('myStyle', '');
    if (myStyle !== '') {
        $("#colors").attr("href", myStyle);
    $('.styleswitch').on('click', function () {
        $("#colors").attr("href", $(this).attr('resource'));
        $.jStorage.set('myStyle', $(this).attr('resource'), { TTL: 28800000 });
        return false;
Here is the HTML in the <head> section:
<link rel="stylesheet" type="text/css" href="css/colors.css" id="colors"/>

And here are the buttons for selecting styles (in the <body> section):
<h4>Colour scheme</h4><button type="button" class="button styleswitch" resource="css/colors.css">Pink</button><br/><button type="button" class="button styleswitch" resource="css/colors-lime.css">Lime</button><br /><button type="button" class="button styleswitch" resource="css/colors-muted.css">Muted colours</button><br /><button type="button" class="button styleswitch" resource="css/colors-dark.css">Dark  colours</button><br /> 

Popular posts from this blog

Tooltip popup box for Moodle