0

I'm currently able to dynamically change style rules directly via JS, but I find this rther limiting and I'd rather be able to to hot-swap entire CSS stylesheet files. Any suggestions?

My code:

<label>Themes :</label>
<select name="background" id="bg" onchange="changeBg(this)">
    <option value="white">Default</option>
    <option value="#444">Dark</option>
    <option value="teal">Teal</option>
</select>

// Changing Themes
function changeBg(x){
    var body = document.getElementById('body');
    body.style.backgroundColor = x.value;
}

And perhaps I'd have multiple stylesheet definitions, like so:

<!-- Themes -->
    <link type="text/css" rel="stylesheet" media="all" href="style.css" id="theme1_css">
    <link type="text/css" rel="stylesheet" media="all" href="themes/dark.css" id="theme2_css">
    <link type="text/css" rel="stylesheet" media="all" href="themes/teal.css" id="theme3_css">
8
  • 1
    Save on HTTP requests and use a master class name in <html>. Change themes CSS to in such way they become .dark body { /* props */ }, .teal body { /* props */ } Commented Jan 2, 2018 at 14:41
  • 1
    See stackoverflow.com/questions/19844545/… Commented Jan 2, 2018 at 14:41
  • Or see this stackoverflow.com/questions/13735247/… and instead of elements by tag name, you can give the link an id and just target that to change it's href Commented Jan 2, 2018 at 14:50
  • it's not working out with onchange event @Stuart Commented Jan 2, 2018 at 14:52
  • The problem is, I'm using bootstrap too. so if i replace all link tags with new css tag then all link include the bootstrap will removed too. I don't want that way Commented Jan 2, 2018 at 15:18

2 Answers 2

0

So I edit the js script into this:

// Changing Themes
function changeBg(x){
    var link = document.getElementById('theme1_css');
    link.href = 'themes/' + x.value + '.css';
}

credit: thanks to @Pete

Sign up to request clarification or add additional context in comments.

Comments

0

The basic idea is that you can use the disabled property to set/unset themes:

<link rel="stylesheet" type="text/css" href="dark.css" data-theme="dark">
<link rel="stylesheet" type="text/css" href="light.css" data-theme="light">

And:

function setTheme(theme) {
    var styles = document.querySelectorAll('link[rel="stylesheet"]');
    styles.forEach(function(style) {
        var styleTheme = style.getAttribute('data-theme');
        style.disabled = styleTheme && styleTheme !== theme;
    });
}

Now set theme with something like:

setTheme('light');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.