kannan D.S
kannan D.S

Reputation: 1101

jQuery click event style sheet changing not working

jQuery click event style sheet changing not working.I am trying to change the style sheet using jQuery, The style sheet is changing but style sheet properties are not working. How can I solve this issue.

$(document).ready(function() {
$(".theme1").click(function() {
$("#switch").attr({href : "theme1.css"});
});
});

Upvotes: 0

Views: 85

Answers (3)

Pedram
Pedram

Reputation: 16575

Try this:

$('#toggleStyle').click(function (){
   $('link[href="style.css"]').attr('href','styleNew.css');
});

jsFiddle

just if you want to keep new style if user do a reload, you should set a cookie to keep user setting.


Multi CSS with select option:

$('#ChangeStyle').change(function (){
    var val = $(this).val();
   $('link[rel="stylesheet"]').attr('href',val+'.css');
});

Html:

<select id="ChangeStyle">
  <option value="Style1">Style 1</option>
  <option value="Style2">Style 2</option>
  <option value="Style3">Style 3</option>
</select>

Multi CSS with buttons:

$('.toggleStyle').each(function (){
$(this).click(function (){
    var rel = $(this).attr('rel');
   $('link[rel="stylesheet"]').attr('href',rel+'.css');
});
});

Html:

<a class="toggleStyle" rel="Style1">Style 1</a>
<a class="toggleStyle" rel="Style2">Style 2</a>
<a class="toggleStyle" rel="Style3">Style 3</a>
<a class="toggleStyle" rel="Style4">Style 4</a>
<a class="toggleStyle" rel="Style5">Style 5</a>

Upvotes: 1

Nikhil Batra
Nikhil Batra

Reputation: 3148

Yes you can update the new style-sheet by updating your <link> and appedning it to the <head> as follow:

$('<link/>', {rel: 'stylesheet', href: 'style1.css'}).appendTo('head');

See the plunkr

Here the h1 has color:red which changes to green as the style-sheet source is changed from style.css to style1.css on clicking the change style button.

Here is the html code:

<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script data-require="jquery" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello Plunker!</h1>
    <a class="clickToStyle">change Style</a>
  </body>

</html>

It has style.css as the original css.

In the JS:

$(document).on('click','.clickToStyle',function(){
  $('<link/>', {rel: 'stylesheet', href: 'style1.css'}).appendTo('head');
})

The stylesheet source is replaced with style1.css and hence new styles get applied.

Upvotes: 0

Domain
Domain

Reputation: 11808

Try the following code:

<head><link id="test" href="yourstyle.css" rel="stylesheet" type="text/css" /></head>

Jquery::

​$(document).ready(function() {
  $(".theme1").click(function() {
  $("#test").attr("href", "newStyle.css");
  });
});

Upvotes: 0

Related Questions