Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Theme switcher in JS

I want to save the user preferred theme (light/dark) in cookies. Can someone help me with it? I'm really bad at JS. I submit my current script.

Stylesheets:

<link rel="stylesheet" href="custom.css" id="pagestyle2" type="text/css" charset="utf-8"/>
<link href="file-upload.css" id="pagestyle4" rel="stylesheet">
<link href="bootstrap.css" id="pagestyle3" rel="stylesheet">
<link href="hg.css" id="pagestyle" rel="stylesheet">

Switcher:

<li class="nav-item" id="pagestylechoose">
    <a href="#" onclick="swapStyleSheet('dark.css');swapStyleSheet2('custom-dark.css');swapStyleSheet3('bootstrap-dark.css');swapStyleSheet4('file-upload-dark.css')"></a>
</li>

Switcher JS:

    function swapStyleSheet(sheet) {
        document.getElementById('pagestyle').setAttribute('href', sheet);
    }
    function swapStyleSheet2(sheet) {
        document.getElementById('pagestyle2').setAttribute('href', sheet);
    }
    function swapStyleSheet3(sheet) {
        document.getElementById('pagestyle3').setAttribute('href', sheet);
    }
    function swapStyleSheet4(sheet) {
        document.getElementById('pagestyle4').setAttribute('href', sheet);
    }
like image 669
John Cloud Avatar asked May 21 '26 08:05

John Cloud


1 Answers

Although it requires a little modification of your CSS, there is another solution instead of having to load different style sheets.

Load a default version, for this example, lets say its the light version. Then when the visitor wants the dark version, a class is added to the BODY called dark.

Then within your DARK version of the CSS, just add body.dark to the beginning of all CSS selectors.

Fiddle: https://jsfiddle.net/Lw7461ey/ (SO Snippets blocks localstorage so I used jsfiddle)

This way you can load all of the CSS files at once, you can even compress them if you wanted to.

var ChangeTheme = document.querySelector(".ChangeTheme");

if(localStorage.getItem("theme") === undefined){
   localStorage.setItem("theme","light");
}

function setTheme(){
   document.body.classList.remove("dark");
   document.body.classList.remove("light");
   document.body.classList.add(localStorage.getItem("theme"));
}

ChangeTheme.addEventListener("click",function(){
   localStorage.setItem("theme",(localStorage.getItem("theme") === "dark") ? "light" : "dark");
   setTheme();
});

setTheme();

For your CSS for example

Lets say in light you have:

a{color:#000000;}

For dark, just change it to:

body.dark a{color:#ffffff;}
like image 179
imvain2 Avatar answered May 23 '26 22:05

imvain2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!