microsynthera.net

e-mail rss

Making A Darkmode Switch For Your Site

This guide will assume darkmode as the default. The basic idea is to create variables in CSS that change dynamically with the assignment of a class on the body element of your page. To keep the settings, you make cookies on the client machine to store the preferred setting. This is how you do it.

A good place to start is with the thing the user will interact with: A button in this case. Put one of these in your HTML.

<button id="theme-toggle">Toggle Theme</button>

Then we can move on to the next logical thing: The colors the user will see. Put something like this in your CSS.

:root {
  --bg-color: #000;
  --unvisit-link: #fff;
  --visited-link: #777;
  --text-color: #999;
}

body.light-mode {
  --bg-color: #fff;
  --unvisit-link: #666;
  --visited-link: #aaa;
  --text-color: #000;
}

Then, finally, to make the change and save it, we turn to our Javascript. In our external script, we add:

const themeToggleBtn = document.getElementById('theme-toggle');

const currentTheme = localStorage.getItem('theme');

if (currentTheme === 'light') {
  document.body.classList.add('light-mode');
}

themeToggleBtn.addEventListener('click', () => {
  document.body.classList.toggle('light-mode');

  if (document.body.classList.contains('light-mode')) {
    localStorage.setItem('theme', 'light');
  } else {
    localStorage.setItem('theme', 'dark');
  }
});

This does the work of putting (or taking) the light-mode class on (or from) our HTML body dependent on the state of theme in the local storage. It also sets the theme variable if the button is pressed.

That’s about it! Pretty straight forward, right? o pona ale, oke?




Last updated on 18-Oct-2026.