Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 326
Michael Schwartz Avatar asked Oct 21 '11 08:10

Michael Schwartz


People also ask

Can we change CSS using jQuery?

You can change CSS using the jQuery css() method which is used for the purpose of getting or setting style properties of an element. Using this method you can apply multiple styles to an HTML all at once by manipulating CSS style properties.

How do you change the style of an element using jQuery?

The css() method in JQuery is used to change the style property of the selected element.


2 Answers

$('#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.

like image 79
Val Avatar answered Oct 07 '22 15:10

Val


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")); } 
like image 30
Tetaxa Avatar answered Oct 07 '22 15:10

Tetaxa