Add dark mode to your website with just a few lines of code
Tags: javascript, tutorial, beginners, codenewbie
Published: 2020-02-17 00:10:21

---
canonical_url: https://inspiredwebdev.com/add-dark-mode-to-your-website
---

> This article was originally posted on my [blog](https://inspiredwebdev.com/add-dark-mode-to-your-website). Head over to [inspiredwebdev.com](https://inspiredwebdev.com) for more articles and tutorials. Check out my **JavaScript course** on [Educative](https://www.educative.io/courses/complete-guide-to-modern-javascript?aff=BqmB) to learn everything from ES6 to ES2019.

&nbsp;

Hi, I am Alberto Montalesi, a full-stack self-taught developer. I create practical JavaScript tutorials and courses on my website [inspiredwebdev.com](https://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`.

&nbsp;

## 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:

```css
@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](https://caniuse.com/#search=prefers-color-scheme) 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.

&nbsp;

## 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:

```html
<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.

```html
<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:

```js
// 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**.

&nbsp;

## 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:

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

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

```js
// 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.

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`

```js
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:

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

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

Edit: Thanks to [Thomas](https://dev.to/thomasbnt) and [Taufik](https://dev.to/taufik_nurrohman) for corrections and edits.


---

Thank you very much for reading. Follow me on [DevTo](https://dev.to/albertomontalesi) or on my blog at [inspiredwebdev](https://inspiredwebdev.com/) or on [twitter](https://twitter.com/montalesi). Check out [Educative.io](https://www.educative.io/explore?aff=BqmB) for interactive programming courses. 

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

<div className="promotional_banner">
<a href="http://a-fwd.to/5gUojI8" target="_blank">
<img alt="book banner" src="https://raw.githubusercontent.com/AlbertoMontalesi/The-complete-guide-to-modern-JavaScript/master/assets/banner.jpg" />
</a>
<span>Get my ebook on <a href="http://a-fwd.to/5gUojI8" target="_blank">Amazon</a> and <a href="https://leanpub.com/thecompleteguidetomodernjavascript2019" target="_blank">Leanpub</a></span>
</div>