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

albertomontalesi

AlbertoM

Posted on February 17, 2020

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

This article was originally posted on my blog. Head over to inspiredwebdev.com for more articles and tutorials. Check out my JavaScript course on Educative to learn everything from ES6 to ES2019.

 

Hi, I am Alberto Montalesi, a full-stack self-taught developer. I create practical JavaScript tutorials and courses on my website inspiredwebdev.com to inspire other developers to grow and build the career that they want.

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 */
}
Enter fullscreen mode Exit fullscreen mode

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.

 

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" />
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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';

        }
    })
})
Enter fullscreen mode Exit fullscreen 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');
Enter fullscreen mode Exit fullscreen mode

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)  
    })
})
Enter fullscreen mode Exit fullscreen mode

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.

Update: 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');
}
Enter fullscreen mode Exit fullscreen mode

And your css will look like the following:

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

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

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


Thank you very much for reading. Follow me on DevTo or on my blog at inspiredwebdev or on twitter. Check out Educative.io for interactive programming courses.

Disclaimer: Links to Amazon and Educative are affiliate links, purchases you make will generate extra commissions for me. Thank you


book banner

Get my ebook on Amazon and Leanpub

💖 💪 🙅 🚩
albertomontalesi
AlbertoM

Posted on February 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Math()
javascript JavaScript Math()

June 21, 2023

Why 0.1+0.2==0.3 False?
javascript Why 0.1+0.2==0.3 False?

August 29, 2022

Creating and Consuming Custom Events
javascript Creating and Consuming Custom Events

August 10, 2022

Utilizing a Nested GET Request
javascript Utilizing a Nested GET Request

July 3, 2022