With the growing popularity of dark mode in modern web interfaces, it’s become increasingly important for developers to implement this feature. Whether you’re a seasoned professional or just starting with web development, this guide will walk you through the process of creating a toggle switch for dark and light themes in JavaScript.

Step 1: Detecting the User’s Preference

Before we start writing our JavaScript code, we need to check the user’s preferred colour scheme. We can do this using the window.matchMedia() method.


const prefersDarkScheme = window.matchMedia("(prefers-colour-scheme: dark)").matches;

if (prefersDarkScheme) {
  document.body.classList.add("dark-theme");
} else {
  document.body.classList.add("light-theme");
}

This code checks the user’s operating system colour scheme preference and adds a class (dark-theme or light-theme) to the body of your document accordingly.

Step 2: Loading the Appropriate Styles

Next, we’ll need to define our colour schemes in CSS. We’ll create two classes: one for our light theme and another for our dark theme.


/* Default to light theme */
body {
  background-colour: white;
  colour: black;
}

/* Dark theme */
body.dark-theme {
  background-colour: black;
  colour: white;
}

/* Light theme */
body.light-theme {
  background-colour: white;
  colour: black;
}

You’ll likely have more style changes, but this example serves to illustrate the idea. Make sure to import your CSS file into your HTML document.

Step 3: Adding a Toggle Switch

Finally, we’ll add a button to our HTML that allows users to switch between our dark and light themes.


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

We can then add an event listener to this button in JavaScript, which will switch the theme whenever it’s clicked.


const themeToggle = document.getElementById("theme-toggle");

themeToggle.addEventListener("click", function() {
  const currentTheme = document.body.classList.contains("dark-theme") ? "dark" : "light";
  
  // Switch from light to dark or from dark to light
  if (currentTheme === "dark") {
    document.body.classList.replace("dark-theme", "light-theme");
  } else {
    document.body.classList.replace("light-theme", "dark-theme");
  }
});

Remembering the User’s Choice

The above code doesn’t remember the user’s choice, so each time the user revisits your website, the colour scheme will reset to the operating system’s preference. If you want to store the user’s choice, you can use the localStorage object:


// Check local storage then system preference for theme
let currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : (window.matchMedia("(prefers-colour-scheme: dark)").matches ? "dark" : "light");

// Set the body class based on the current theme
document.body.classList.add(currentTheme + "-theme");

// Click event handler
themeToggle.addEventListener("click", function() {
  currentTheme = document.body.classList.contains("dark-theme") ? "dark" : "light";
  
  // Switch from light to dark or from dark to light
  if (currentTheme === "dark") {
    document.body.classList.replace("dark-theme", "light-theme");
    currentTheme = "light";
  } else {
    document.body.classList.replace("light-theme", "dark-theme");
    currentTheme = "dark";
  }

  // Save the current theme in local storage
  localStorage.setItem('theme', currentTheme);
});

In this enhanced version, the user’s theme choice is stored in local storage and checked on page load. If there’s no saved choice, the code defaults to the operating system’s preference. Then, each time the user changes the theme, their choice is saved to local storage.

That’s all there is to it! With a bit of JavaScript and CSS, you can provide a more comfortable and personalised user experience on your website. Whether your users prefer dark or light mode, they’ll appreciate the option to choose.

Please note: the information in this post is correct to the best of our endeavours and knowledge at the original time of publication. We do not routinely update articles.