Add dark mode to your website with just a few lines of code

Add dark mode to your website with just a few lines of code
Check out my Github for my free-to-read JavaScript Ebook that covers all the new features from ES6 to 2019. If you want find a great place for interactive tutorials, i recommend Educative where I'm currently finishing to build my JavaScript course.
This website contains affiliate links. See my disclosure about affiliate links here

Dark mode has become incredibly popular in the last year and all popular apps nowadays offer a toggle to turn it on.

In this short tutorial we are going to look at how to add support for dark mode in your website in different ways: first with just CSS and lastly with a toggle built with JavaScript.

Adding Dark Mode support with CSS

If you don't want to get too fancy with dark mode and just want your website to change color palette if the user is using a browser with dark mode enabled, CSS is going to be enough for you.

Inside of your CSS file, write this media query:

@media (prefers-color-scheme: dark) {
    /* all your styles for dark mode here */
}

With this media query, we can define a set of custom styles to apply when the user is browsing with dark mode enabled.

According to CanIUse.com the support is at around 78%, leaving out Internet Explorer and Edge (not Edge Chromium).

If you are not working on enterprise software where you really have to worry about users still using Internet Explorer, I think that this media query can work well.

The downside of this method is that your user won't have control over how they want to view your website so I would consider it only if you don't have time or don't want to implement a toggle.

educative banner

Toggle Dark Mode with JavaScript

Let's now go one step further and implement a toggle for Dark Mode with JavaScript.

To be able to do that you will need to create two different stylesheets, one for each theme (light and dark). If you need, you can create a third stylesheet which will contain non-theme related styles.

The first step will be to define a default theme stylesheet in the head of our html like so:

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

What we are going to do now is to create a button to swap that stylesheet with another one.

Go ahead and create a button like the following and put it wherever you like, preferably at the top of the page for quicker access by the user.

<button id="theme-toggle">Switch to dark mode</button>

Now that we have a simple button, let's add some JavaScript to it. Open your JavaScript file and write the following lines of code:

// this one is jut to wait for the page to load
document.addEventListener('DOMContentLoaded', () => {

    const themeStylesheet = document.getElementById('theme');
    const themeToggle = document.getElementById('theme-toggle');
    themeToggle.addEventListener('click', () => {
        // if it's light -> go dark
        if(themeStylesheet.href.includes('light')){
            themeStylesheet.href = 'dark-theme.css';
            themeToggle.innerText = 'Switch to light mode';
        } else {
            // if it's dark -> go light
            themeStylesheet.href = 'light-theme.css';
            themeToggle.innerText = 'Switch to dark mode';

        }
    })
})

This code is simply adding an event listener to our button so that every time we click it it will look at the href of our stylesheet and toggle between dark and light. We are also changing the text of the button itself to reflect the change in the theme.

You can play around with the button itself and define some neat icons to better differentiate between dark and light themes.

If you try the above code you will see that when you click the button the stylesheet changes but there is one problem.

Can you guess what the problem may be?

If you are thinking that the next time a user comes back to the website they will have to click again the button to toggle again the theme, then you guessed right.

At the moment the user choice is not saved anywhere so once they leave the site and come back they will have to switch theme again.

Luckily there's a quick way that allows us to overcome this problem and that is LocalStorage.

Saving users' preferences in localStorage

As the name implies, preference set to it will be stored locally on your browser so if your user changes browser or device they will lose their choice of theme but most of the time they will probably come back to your site using the same device so this can be a quick and effective way to store their preference.

LocalStorage can store key value pairs and we can use it like this:

localStorage.setItem('theme', 'dark-theme.css');

Let's go ahead and add it to our previous code:

// this one is jut to wait for the page to load
document.addEventListener('DOMContentLoaded', () => {

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

As you can see in the code above, on page load we do a check to see if there is a theme preference stored in localStorage by using localStorage.getItem('theme').

If we find something, we then apply it right away, restoring the user's preferences.

I've also updated the code that runs when we click a button, including this line localStorage.setItem('theme',themeStylesheet.href) to store the user selection.

Now we have a fully functional light-dark theme toggle that will remember the user selection, improving considerably the user experience.

What's great is that this took only 10 minutes to do!

Remember that you are not limited to a dark-light theme, you can have as many as you want and you can even get fancy with them.

A few last words about localStorage: its support is now more than 93% so you can confidently use it without worrying too much about legacy browsers since it's supported even on IE8-9-10!.

Another way to quickly store user preferences, other than localStorage, are sessionStorage which, as the name implies persists only for the current session until the browser session is active which does not suit our case scenario well.

One thing to know about both localStorage and sessionStorage is that they stick to the same-origin policy meaning that if you access your website over both Http and Https, your choice of the theme made over https won't be reflected over Http.

If you start wondering why your preference is not being saved, knowing this little caveat can help you avoid spending half an hour trying to guess what's the issue.

Implement Dark Mode with a single css file

Another way of achieving the same result, but with using only one styleheet would be to toggle a global class on the body.

Add this to your JavaScript

button.addEventListener('click', () => {
    document.body.classList.toggle('dark');
    localStorage.setItem('theme', document.body.classList.contains('dark') ? 'dark' : 'light');
});

if (localStorage.getItem('theme') === 'dark') {
    document.body.classList.add('dark');
}

And your css will look like the following:

/* Light mode */
body {
  background: #fff;
  color: #000;
}

/* Dark mode */
body.dark {
  background: #000;
  color: #fff;
}

Edit: Thanks to Thomas and Taufik for corrections and edits.


Thank you very much for reading. Follow me on DevTo or on Twitter for more.

complete guide to modern javascript alberto montalesi ebook bannerGet my ebook on Amazon and Leanpub or get my course on Educative


NEWEST ARTICLES




ABOUT ME

author alberto montalesi profile picture

Alberto is a software developer specialized in building enterpise software using Angular and author of the 'Complete guide to Modern JavaScript' ebook and course. In his free time he writes articles and tutorials on InspiredWebDev.com and Dev.to

You can read more about him here