0

I'm trying to change css stylesheet by clicking on a button.

<head>    
<link id='link01' rel="stylesheet" href="blue.css">  
</head>

JS

$('.pointcolors').click(function(){
    var theme = $(this).attr('data-theme') + '.css';
    console.log(theme); // green.css - it's ok
    $('#link01').attr('src', theme);
});

But there is no style changes. Nothing happens.
Any help?

qadenza
  • 9,025
  • 18
  • 73
  • 126
  • You might be changing the URL, but that doesn't necessarily mean it'll load the new one. – Adrian Wragg Dec 23 '16 at 14:36
  • 1
    Possible duplicate of [Can I load external stylesheets on request?](http://stackoverflow.com/questions/2126238/can-i-load-external-stylesheets-on-request) – Adrian Wragg Dec 23 '16 at 14:36

4 Answers4

3

Change

 $('#link01').attr('src', theme);

To:

 $('#link01').attr('href', theme);

If you look at your link tag, the attribute that contains the filename is "href", not "src".

ADyson
  • 57,178
  • 14
  • 51
  • 63
3

I think:

$('#link01').attr('src', theme);

Should be:

$('#link01').attr('href', theme);

How to change the href for a hyperlink using jQuery

Community
  • 1
  • 1
Wouter den Ouden
  • 1,523
  • 2
  • 17
  • 44
0

You can do it like this:

Use jQuery's .attr() to change the href property of link tag.

$(function() {
 $("#block a").on('click', function() {
        theme = $(this).data('theme');
  $("#link01").attr("href", theme + '.css');
        console.log("Stylesheet changed to: " + $("#link01").attr("href"));
  return false;
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link id='link01' rel="stylesheet" href="blue.css">  
<div id="block">
  <a href="#" data-theme="green">Change Stylesheet Link</a>
</div>

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
-1

Changing src to href should work.

$('#link01').attr('href', theme);
Jeroen
  • 1,168
  • 1
  • 12
  • 24