Search

Adding Dark Mode Option to a Website with localStorage

Dark Mode or Dark Theme has become quite common on websites lately. And with this trend existing in iOS, macOS & Windows, most systems or applications have already adopted those dark themes.

“Dark Mode” makes your website more attractive to users who prefer darker colors. The user experience will be better if you provide functionality to switch between the light theme and dark theme.

In this short post, I will show you how to add Dark Mode to your website using localStorage.

Create Relevant CSS Files

Start by creating two CSS files, one named light-theme.css that is empty, and the other named dark-theme.css containing all the CSS settings for the Dark Mode on your site.

The light-theme.css file will be empty, and the Light Theme is actually the standard CSS of the site. It may seem a bit redundant or less efficient, but if you know or manage to create a better way to implement this, we would be happy if you shared it in the comments.

Add these files to the CSS directory on your site. Then, add a link to the CSS file in the site’s head as follows:

<link id="themeCssLink" rel="stylesheet" type="text/css" href="/path-to/light-theme.css"/>

Note: Adjust the path to the file according to its location in the site directory.

Create the Dark Mode Toggle Button

To create the button that will switch between modes, add the following markup to your site’s footer:

<button id="toggleButton">Change Contrast</button>

If you want to style/position it as it appears on the Savvy Blog, you can use the following CSS:

#toggleButton {
    right: 10px;
    left: auto;
    position: fixed;
    bottom: 14px;
    z-index: 999999;
    display: inline-block;
    text-indent: -999999px;
    width: 40px;
    height: 40px;
    background: linear-gradient(-45deg, #ffd600, #ffd600 49%, #fefefe 49%, #fefefe 51%, #2d2d2d 51%);
    border-radius: 50%;
    border: 0;
}

JavaScript to Switch Between Modes

To maintain user preferences regarding the mode in which they want to view the site, we will use localStorage. If you’re not familiar, localStorage is functionality that allows storing key/value pairs in the browser.

The data in localStorage is preserved in the browser even after page refresh and even after the user initializes the browser.

You can check which values are stored for a specific site in localStorage using the browser’s Developer Tools under the Application tab. Here is an example of how it looks in Chrome Dev Tools:

LocalStorage In Chrome Dev Tools

In any case, let’s look at the code we use to store this value in the browser, and then we’ll explain it a bit. This is the function:

document.addEventListener('DOMContentLoaded', () => {
    const themeStylesheet = document.getElementById('themeCssLink');
    const themeToggle = document.getElementById('toggleButton');
    const storedTheme = localStorage.getItem('themeColor');

    if (storedTheme) {
        themeStylesheet.href = storedTheme;
    }
    themeToggle.addEventListener('click', () => {
        // if it's dark -> go light
        if (themeStylesheet.href.includes('dark')) {
            themeStylesheet.href = '/path-to/light-theme.css';
            themeToggle.innerText = 'Switch to light mode';
        } else {
            // if it's light -> go dark
            themeStylesheet.href = '/path-to/dark-theme.css';
            themeToggle.innerText = 'Switch to dark mode';
        }
        // save the preference to localStorage
        localStorage.setItem('themeColor', themeStylesheet.href)
    })
})

We execute the function only after DOMContentLoaded, which is an event indicating that all HTML is loaded and parsed without waiting for the loading of images, CSS files, etc.

Before explaining the code, please note that you should update the paths in lines 12 and 16 to the correct paths of the CSS files you created earlier.

A Few Words About the Code Above

The code is quite straightforward – in line 2, we target the same link to the CSS file added in the site’s head and place it in a variable named themeStylesheet.

In line 3, we target the button we created, the one that toggles between dark and regular mode, and place it in a variable named themeToggle.

In line 4, we check if there is data in the browser’s localStorage with the key named themeColor.

If it exists, meaning if the user pressed the button before and the preferred mode setting is already in the localStorage, then we determine that the CSS file link will contain the address to the relevant CSS file, either dark-theme.css or light-theme.css.

If it’s not clear, the value of that key we store in localStorage will be the URL address of the relevant CSS file, either one of those files we created earlier – light-theme.css or dark-theme.css.

In line 9, we listen for the button click event. If the CSS file address contains the word dark, we switch the address to the light CSS file, i.e., light-theme.css that doesn’t contain any special CSS settings. And of course, the opposite action occurs if the address contains the word light.

In line 20, we ensure that if nothing exists in localStorage, the file address for light-theme.css is stored, which doesn’t contain any special settings.

Summary

In this post, we explained how to add a dark mode to your website. I didn’t mention it in the post, but using CSS Variables can be excellent in this case.

If you have any questions, feel free to use the comments below. Besides, if you see how this can be implemented better, we would appreciate it if you share it with us in the comments as well. Good luck 🙂

Roee Yossef
Roee Yossef

I develop websites & custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

0 Comments...

Leave a Comment

Quick Navigation

Up!
Blog