DEV Community

loading...

Theme Changer using localStorage and CSS custom properties(variables).

nicklasspendler profile image NicklasSpendler ・2 min read

If you have never used localStorage before check out Mozilla docs, we will be using a little different Syntax than shown, but it will give you an idea on how Localstorage works

First of all create a stylesheet and link it in your HTML

<link rel="stylesheet" href="main.css">

Then create a button and give it a class

<button class="changeTheme">Change Theme</button>

Then add a script tag on the bottom of your HTML

<script src="main.js"></script>

Your HTML should now look like something like this

<html>
<head>

    <link rel="stylesheet" href="main.css">

</head>

<body>
    <button class="changeTheme">Change Theme</button>

    <script src="main.js"></script>
</body>
</html>

In the CSS file we start off by creating our variables and assign it to what ever we want the change the color of. In this case I create an variable called themeColor and use it on the background-color on the body. The reason --themeColor is empty is because we give it its property through the javascript. We do this to prevent the page from flickering.

body{
    --themeColor: ;
    background-color: var(--themeColor);
}

Time for the javascript, start off by making an variable for your button.

let themeChangerBtnElem = document.querySelector('.changeTheme')

Now we want to create the localStorage but before we create it we have to check if it already exist. We do that to prevent overwriting it.

if(localStorage.currentTheme == null){
    console.log('currentTheme does not exist', )
    localStorage.currentTheme = "blue"
}else{
    console.log('CurrentTheme does exist', )
    console.log('Localstorage: ', localStorage.currentTheme)
}

Then make an updateUI function, we call this everytime we want to update our page so remember to call the function somewhere in your code. Whats happening is that we set the property of the --themeColor depending on the localStorage

updateUI();
function updateUI(){
    if(localStorage.currentTheme == "blue"){
        document.body.style.setProperty("--themeColor", "blue")
    }else if (localStorage.currentTheme == "grey"){
        document.body.style.setProperty("--themeColor", "grey")
    }

at last we give our button an eventListener which change the localStorage.
If the localStorage is blue, change it to grey and vice versa. And then we call our updateUI function.

themeChangerBtnElem.addEventListener('click',()=>{
    if(localStorage.currentTheme == "blue"){
        localStorage.currentTheme = "grey"
    }else if (localStorage.currentTheme == "grey"){
        localStorage.currentTheme = "blue"
    }
    updateUI();
});

This tutorial were requested by a fellow student, I hope it were helpful

Discussion (0)

pic
Editor guide