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.

Switching stylesheets using jquery

Try using style elements with type set to text/plain ; on click of input type="button" set style type="text/css" to text content of style type="text/plain" having class same as id of input type="button" clicked . Approach maintains all css in same document , without need to request external style sheet at each toggle of styles

$("input[type=button]").click(function() {
  $("[type$=css]").text($("." +
<script src=""></script>
<style type="text/css">
<style type="text/plain" class="theme1">
  /* Theme 1 */ 
  body { background: #ff4455; }
<style type="text/plain" class="theme2">
  /* Theme 2 */ 
  body { background: #ee7744; }

  <input type="button" id="theme1" value="theme1">
  <input type="button" id="theme2" value="theme2">

There should be many similar questions and answers, here's one anyway.

    <link href="css/sheet1.css" rel="stylesheet" type="text/css" id="sheet1">
    <script src=""></script>
    <input type="button" id="theme1">
    <input type="button" id="theme2">
    <script type="text/javascript">
    $(document).ready(function () {
            $('head').append('<link href="css/sheet1.css" rel="stylesheet" id="sheet1" />');
            $('head').append('<link href="css/sheet1.css" rel="stylesheet" id="sheet2" />');

Simple style swicher with less

You can change the href attribute of your link tag when click on the button

So using your example

$('li').on('click', function() {

This is a basic example, you can give your link tag an id and target it that way

Also see How do I switch my CSS stylesheet using jQuery?