Build a Light/Dark Theme Toggle with JavaScript

Build a Light/Dark Theme Toggle with JavaScript

The fun part of building sites is adding functionality, let's learn how to make a Theme Toggle!

·

4 min read

One of the things that make your page more dynamic is adding functionality with JavaScript. In this article i'll walk you through making a fun and easy theme toggle using CSS and JavaScript!

final_6149141579097000e845fe01_797176

There are endless possibilities on what you can do with it so let's get started!

Let's set up our HTML document

We have to add a 'wrapper' for our theme-switch elements in which we're going to have our label, type checkbox and ultimately our slider that will contain our smiley/moon face.

<div class="theme-switch-wrapper"> 
    <label class="theme-switch" for="checkbox">
        <input type="checkbox" id="checkbox"/>
            <div class="slider round"></div>
    </label>
</div> 

<h1> Hi! This is test text </h1>
<h2> This is smaller test text </h2>
<h3> Smol test text </h3>

It's going to look like this:

Screenshot (71)

I know! I know! But remember what i always say, you gotta trust the process!

Let's work on the CSS

First we need to add our default value styles, or :root styles. These are the ones we are going to see on our 'light' mode:

:root{
    --font-color: #66545e;
    --background-color: rgb(255, 194, 204);
  }

And of course the ones for our 'dark' mode:

  [data-theme="dark"] {
    --font-color: #525353;
    --background-color: #cde2e0;
}

Also let's add some styles to center everything:

body{
  display: flex;
  align-items: center;
  justify-content:center;
  flex-direction: column;
  background-color: var(--background-color);
}

h1, h2, h3{
  color: var(--font-color);
}

Now, you might've noticed i used var(--background-color); and var(--font-color); this is going to take the variable (after we add our JavaScript) of the background or font color from either the 'light' mode or the 'dark' mode if it's clicked.

It's probably looking a bit like this now:

Screenshot (72)

But that's a SUPER UGLY theme toggle yukkk!! Let's fix that:

*::before, *::after {    
    margin: 0;
    padding: 0;
}

If you'd like to know more about ::before, ::after and content click me i take you to the article!

But we don't want our theme toggle to be that checkbox box style, so let's just hide it.

.theme-switch {    
    display: inline-block;
    height: 34px;
    position: relative;
    width: 60px;
    border-radius: 15px;
}

.theme-switch input {
    display: none;    
}

Stay with me here, let's add some life to our slider! That's where all the magic happens:


.slider {
    background-color: gray;
    bottom: 0;
    cursor: pointer;
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
    transition: .4s;

  }

.slider::before {    
    bottom: 4px;
    height: 26px;
    left: 4px;
    position: absolute;
    transition: .4s;
    width: 26px; 
    content:"🌞";

}

input:checked + .slider {
    background-color: gray;
}

input:checked + .slider::before {
    transform: translateX(26px);
    content:'🌙';

}

.slider.round {
    border-radius: 15px;
}

.slider.round::before {
    border-radius: 10%;
}

We're working with this:

final_61494a680d154800fefaba65_872642

But nothing's happening :(

Add JavaScript

First my friend, we have to 'select' the element we're going to be working with from our HTML document.

const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');

Now we need to make a function to handle the change when an event, in this case the 'click' happens.

  • We are looking for an event
  • When it happens we set the data-theme to dark
  • Else it's going to be data-theme light
  • We add an event listener for the 'change' to false

function switchTheme(e) { 
        if (e.target.checked) { 
            document.documentElement.setAttribute('data-theme', 'dark')
        }
        else { 
            document.documentElement.setAttribute('data-theme', 'light')
        }    
    }
    toggleSwitch.addEventListener('change', switchTheme, false)

That should get it working!! But we would want to make our user's life easier by making sure the page remembers the theme preference, right? Let's do it with Local Storage.

Add Local Storage

This step is totally optional, my friend! :)

We just need to add a couple more lines of code in our JavaScript. In our switchTheme(e) function we add local storage. Like this:

    function switchTheme(e) { 
        if (e.target.checked) { 
            document.documentElement.setAttribute('data-theme', 'dark')
            localStorage.setItem('theme', 'dark'); 
        }
        else { 
            document.documentElement.setAttribute('data-theme', 'light')
            localStorage.setItem('theme', 'light'); 
        }    
    }

Now we just have to actually store it and get it when the user is on the site again:

const savedTheme = localStorage.getItem('theme') ?  localStorage.getItem('theme') : null;

if (savedTheme) {
    document.documentElement.setAttribute('data-theme', savedTheme);

    if (savedTheme === 'dark') {
        toggleSwitch.checked = true;
    }
}

And that should be it, my friend! Be on your way with your new theme toggle :)

final_6149141579097000e845fe01_797176


Thank you so much for reading!!

Adding functionality to your sites with JavaScript is such a fun experience for both the user and the developer. I really hope you enjoyed this one :)

Don't hesitate to contact me and let me know what you think in the comments!

☕If you enjoy my content Buy me a coffee It'll help me continue making quality blogs💕

💙Follow me on Twitter to know more about my self-taught journey!

💜Make sure to check out more upcoming articles on my Web Design for Beginners Series

❤️ Also subscribe to my Youtube Channel !

🖤And for more content and tips on TikTok !

💛This is also part of the Technical Writer Journey Series! Check that one out too.