Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to add a dark mode toggle

Short answer

Describe colors with CSS variables, change them for the dark class and switch the class with a button:

<style>
  :root { --bg: #ffffff; --text: #222222; }
  :root.dark { --bg: #1e1e1e; --text: #eeeeee; }
  body { background: var(--bg); color: var(--text); }
</style>
<button id="theme">Toggle theme</button>
<script>
  document.getElementById('theme').addEventListener('click', () => {
    document.documentElement.classList.toggle('dark');
  });
</script>

Remembering the choice

Save the theme to localStorage and restore it when the page loads:

const root = document.documentElement;
 
if (localStorage.getItem('theme') === 'dark') root.classList.add('dark');
 
button.addEventListener('click', () => {
  const isDark = root.classList.toggle('dark');
  localStorage.setItem('theme', isDark ? 'dark' : 'light');
});

The system setting

If the user has not chosen yet, follow the setting of their system:

const saved = localStorage.getItem('theme');
const systemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
 
document.documentElement.classList.toggle('dark', saved ? saved === 'dark' : systemDark);

Common mistake

If the theme is applied at the end of the page, the light version flashes first. Put the script that sets the class in the head, before the styles are shown.

<head>
  <script>
    if (localStorage.getItem('theme') === 'dark') document.documentElement.classList.add('dark');
  </script>
</head>

Thanks for reading!

Donate to the site — we work hard for you.