Categories
CSS HTML JavaScript Web

Adding Dark Mode Toggle To Your Website

What’s wrong with just having light mode and why do you need dark mode on your website? Is dark mode a goofy aesthetic add-on or does it hold more value then meets the eye? How do you add dark mode to your website?

The answer to these questions go further than you might expect.

Adding dark mode to your website is a wonderful goal and it is not that difficult to do from a technical standpoint (more on this soon). However, the question “why should I add dark mode” remains. To understand why dark mode is important we need to understand the problem dark mode solves.

The largest problem dark mode strives to solve is centered around humans (not aesthetics). People are screening more each day. As a result, our physical eyes strain against the brightness, or lightness, of our screens. Our constant screening hurts us on various levels. Just Google “the impact of using screens too much”… 87,0000,000 results should say enough.

Technology like Apple’s True Tone and Night Shift try to help reduce the stress we put our bodies through when using light mode but these technologies are passive. Drak mode is aggressive.

Dark mode looks to make technology more responsive to our human needs. In fact, I consider dark mode a major component of responsive web design.

On a personal level, I have a few floaters in my vision (basically floaters are little stringy things float around casting shadows in your retina that appear as small translucent grey dots or lines in your vision). These floats are not always visible but when I look at a light screen all day I see them a lot more often. Dark mode dramatically reduces how often I see the floaters. Further, bright screens cause migraines for many people… the point is that having one mode (light mode) is not ideal for many people.

In short dark mode is much more than “a goofy aesthetic add-on”. Dark mode is a response to our real human needs.

How do you add dark mode to your website?

The hard part of adding dark mode is composing and achieving the powerful dual aesthetic of dark and light. However, adding a dark mode to your website, at its core, requires very little CSS on operating systems and browsers that support dark mode. All you need is a media query that uses prefers-color-scheme.

/* Light mode CSS */
body {
  background: #fafafa;
  color: #202020;
}

/* Dark mode CSS */
@media (prefers-color-scheme: dark) {
  body {
    background: #202020;
    color: #fafafa;
  }
}

If you are using CSS variables you can dry-up the example above.

:root {
  --text: #202020;
  --background: #fafafa;
}

/* Dark mode CSS */
@media (prefers-color-scheme: dark) {
  :root {
     --text: #fafafa;
     --background: #202020;
  }
}

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

And, just like that. You have the beginnings of dark mode for your website. Now, whenever someone visits your website the design will be customized to their operating system’s preferences.

However, what if you want to add a toggle button to switch between dark and light mode regardless of the operating system’s preferences? To let users customize their preference on the fly via your website you will need a mode toggle button.

Toggling dark and light mode with JavaScript

To add a dark and light mode toggles to your website you will need to use JavaScript, instead of a CSS media query with prefers-color-scheme. For your toggle buttons, I recommend using https://feathericons.com/. There moon and sun icons look very nice.

Place the toggle code immediately after the opening body tag. Adding the JavaScript code directly after the opening body tag keeps the screen from flashing between dark and light mode on every page load.

<body class="light">
<script>
    // A function for toggling the theme
    function toggleTheme() {
        document.body.classList.toggle("light");
        document.body.classList.toggle("dark");

        localStorage.setItem(
            "colorTheme",
            document.body.classList.contains("dark") ? "dark" : "light"
        );
    }

    // Initialize the theme
    if (localStorage.getItem("colorTheme") === "dark") {
        toggleTheme();
    } else if (
        localStorage.getItem("colorTheme") !== "light" &&
        window.matchMedia &&
        window.matchMedia("(prefers-color-scheme: dark)").matches
    ) {
        toggleTheme();
    }
</script>

// your code...

</body>

On a user’s first visit to the website, the JavaScript code detects that user’s current dark mode settings. The JavaScript then applies a class to the body element of light or dark depending on the setting. Finally, the configuration is saved to local storage with the key of colorTheme. We can then hook into the body classes to control the CSS variables used for the design.

Here is the example CSS that works with the JavaScript toggle version of dark mode. Notice, we are no longer using media queries.

/* Light mode CSS */
:root {
  --text: #202020;
  --background: #fafafa;
}

/* Dark mode CSS */
body.dark {
  --text: #fafafa;
  --background: #202020;
}

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

Finally, you can attach the toggleTheme() function as a callback to the click event of your toggle button. The implementation of the button is entirely up to you.

<button onclick="toggleTheme()">Toggle Theme</button>

I do not advocate using the inline onclick HTML attribute. I’ve used it that here for brevity.

In summary, adding dark mode is of great value to users. I deeply hope that web designers and developers will adopt this new component of responsive web design as rapidly as they adopted responsive web design for the mobile form factor.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.