How do I switch my CSS stylesheet using jQuery?


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:


<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"));

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.

Use this :

<link href="Custom.css" rel="stylesheet" />
<link href="Blue.css" rel="stylesheet" />
<link href="Red.css" rel="stylesheet" />
<link href="Yellow.css" rel="stylesheet" />

<select id="changeCss"`enter code here`>
        <option onclick="selectCss(this)" value="Blue">Blue</option>
        <option onclick="selectCss(this)" value="Red">Red</option>
        <option onclick="selectCss(this)" value="Yellow">Yellow</option>

<script type="text/javacript">
function selectCss() {
            var link = $("link[rel=stylesheet]")[0].href;
            var css = link.substring(link.lastIndexOf('/') + 1, link.length)
            $('link[href="' + css + '"]').attr('href', $('#changeCss').val() + '.css');