1
votes

I want to change the name of CSS import dynamically using jquery. from

<link rel="stylesheet" href="css/Theme.css">

to

<link rel="stylesheet" href="css/blueTheme.css">

HTML

<div class="theme-pallete">
   <button class="blue active" data-theme="Theme">Blue</button>
   <button class="golden" data-theme="goldenTheme">Golden</button>
   <button class="purple" data-theme="purpleTheme">Purple</button>
   <button class="pink" data-theme="pinkTheme">Pink</button>
   <button class="red" data-theme="redTheme">Theme</button>
</div>

Jquery

$('.theme-pallete button').on('click', function () {
    var sheetName = $(this).attr('data-theme');
    $('link[href$="Theme.css"]').attr('href', '/css/' + sheetName + '.css');
});

It works fine on local system but problem arise when Base Url comes into the picture

Please note I don't want to hard code the base URL because of it changes based on hosting environment like

app.project.com/baseurl/css/Theme.css
app.project.com/UAT/css/Theme.css
app.project.com/design/css/Theme.css

2

2 Answers

0
votes

You can do it with a function(where 2nd argument would be old value) and replace the method.

$('.theme-pallete button').on('click', function () {
    var sheetName = 'blueTheme';
    $('link[href$="Theme.css"]').attr('href', (i, value) => value.replace(/Theme\.css$/, sheetName + '.css');
});
0
votes

Simply replace the themename with the new then name

function changeCssURL(themename){
 $("button").click(function(){
   $('link[href$="Theme.css"]').attr("href", "app.project.com/UAT/css/"+themename+".css");
  });
}