DEV Community


Posted on

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

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


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


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

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

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.

    --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"
    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

function updateUI(){
    if(localStorage.currentTheme == "blue"){"--themeColor", "blue")
    }else if (localStorage.currentTheme == "grey"){"--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.

    if(localStorage.currentTheme == "blue"){
        localStorage.currentTheme = "grey"
    }else if (localStorage.currentTheme == "grey"){
        localStorage.currentTheme = "blue"

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

Top comments (0)