How do I switch my CSS stylesheet using jQuery?

What I'm working on is simple.

You click on a button (id="themes") and it opens up a div (id="themedrop") that slides down and lists the themes. (I only have two at this point)

<button id="original">Original</button><br />
<button id="grayscale">Grayscale</button>

Now when the site is loaded it loads with style1.css (main/original theme)

<link rel="stylesheet" type="text/css" href="style1.css">

Now what I'm trying to figure out is... How can I have it that when the grayscale button is clicked to change the stylesheet from style1.css to style2.css (note: files are in the same directory)

Any help would be much appreciated.


$('#grayscale').click(function (){
   $('link[href="style1.css"]').attr('href','style2.css');
});
$('#original').click(function (){
   $('link[href="style2.css"]').attr('href','style1.css');
});

Give this a try but not sure if it will work I have not tested it but gd luck.


I would suggest you give the link-tag an id such as theme. Put the name of the css file in a data-attribute on the buttons and use the same handler on them both:

Html:

<link id="theme" rel="stylesheet" href="style1.css">

<button id="grayscale" data-theme="style2.css">Gray Theme</button>

And js:

$("button[data-theme]").click(function() {
    $("head link#theme").attr("href", $(this).data("theme"));
}

You can try to do that by this way:

<link id="original" rel="stylesheet" type="text/css" href="style1.css">
<script>
function turnGrey(){
    //what ever your new css file is called
    document.getElementById("original").href="grey.css";
}
</script>
<button id="grey" onclick="turnGrey">Turn Grey</button><br />