Add a darkmode/lightmode to your website (css & js)

The following tutorial works to add a darkmode to a light website or to add a lightmode to a already dark website.
The main function is a css class in the body tag. We would like to set this via javascript and then design the darkmode or lightmode with this class via css.

<body class="darkmode"> ... </body<body class="lightmode"> ... </body>

The following javascript code sets this class by looking the preferred color scheme of the browser/os.
But because not every browser have this information, it allows to call a function to set the dark/light mode and save the setting to the local storage.

/*!
 * Turn Website into darkmode/lightmode with a css class
 * Darvin Schlüter https://darvin.de
 * Version 1.0
 */

var darkmodeStorage = localStorage.getItem('darkmode');
function toggledarkmode() {
  darkmodeStorage == "true" ? lightmode(true) : darkmode(true);
}
function darkmode(storage = true){
  document.body.classList.add("darkmode");
  document.body.classList.remove("lightmode");
  darkmodeStorage = "true";
  storage ? localStorage.setItem('darkmode', true) : null;
}
function lightmode(storage = true){
  document.body.classList.remove("darkmode");
  document.body.classList.add("lightmode");
  darkmodeStorage = "false";
  storage ? localStorage.setItem('darkmode', false) : null;
}
window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches && darkmodeStorage == undefined ? lightmode(false) : null;
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches && darkmodeStorage == undefined ? darkmode(false) : null;
darkmodeStorage == "true" ? darkmode(false) : null;
darkmodeStorage == "false" ? lightmode(false) : null;

Add this code right after the <body> tag! This is important to avoid flashing lights when the mode is switched.

If you want to add a button to switch darkmode, use these functions: darkmode(), lightmode(), toggledarkmode(). For example like so:

<a onclick="toggledarkmode();">Toggle Dark/Light Design</a>

Now you can add your custom CSS styles for the darkmode / lightmode.

If your website is already dark use the css class “lightmode”. Here is an example.

body {
  color: white;
  background-color: black;
}
.whitemode body {
  color: black;
  background-color: white;
}

If your website is light and you want to add darkmode:

body {
  color: black;
  background-color: white;
}
.darkmode body {
  color: white;
  background-color: black;
}

In some cases you may need to use !important to override the style, but try to avoid it

In this example i used pure black for the darkmode, but you should consider using a dark grey. In this article are some tips about darkmode styling: 8 Tips for Dark Theme Design. Dark theme is one of the most requested… | by Nick Babich | UX Planet

Leave a Reply

Your email address will not be published. Required fields are marked *