jQuery Change CSS File Dynamically

How to change a css file dynamically using nothing but good old fashion jQuery! (it’s kinda like a jQuery stylesheet switcher!)

The jQuery

$(document).ready(function() {
    $("#nav li a").click(function() {
        $("link").attr("href",$(this).attr('rel'));
        return false;
    });
});

OR (a more complex version to swop the css files dynamically)

$(document).ready(function() {
    if($.cookie("css")) {
        $("link").attr("href",$.cookie("css"));
    }
    $("#nav li a").click(function() {
        $("link").attr("href",$(this).attr('rel'));
        $.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
        return false;
    });
});

OR (a version which reduces the flicker which occurs when ths page refreshes with the new css syles after the css is swopped using the relative attribute of the link in the html code).

if($.cookie("css")) {
    $("link").attr("href",$.cookie("css"));
}
$(document).ready(function() {
    $("#nav li a").click(function() {
        $("link").attr("href",$(this).attr('rel'));
        $.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
        return false;
    });
});

The HTML

The html is simple with the css and jQuery files loaded as normal in the header of the html.

<link rel="stylesheet" type="text/css" href="style1.css" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="jquery.cookie.js"></script>
<script>... your jQuery goes here...</script>

Test it out! Here is a couple of links to try it for yourself.

<ul id="nav">
    <li><a href="#" rel="/path/to/style1.css">Default CSS</a></li>
    <li><a href="#" rel="/path/to/style2.css">Larger Text</a></li>
    <li><a href="#" rel="/path/to/style3.css">Something Different</a></li>
</ul>

Source
Demo