Dark mode has become a popular feature on modern websites, offering users an option to switch between light and dark themes. Implementing dark mode can enhance user experience, reduce eye strain in low-light environments, and provide a sleek, modern look to your website. This guide will show you how to add a dark mode toggle to your website using JavaScript and CSS custom properties.

Step 1: Define Light and Dark Mode Styles Using CSS Variables

CSS custom properties (variables) make it easy to switch between light and dark mode by changing color values dynamically. Begin by defining variables for both modes.

Example of CSS Variables for Light Mode:

:root {
  --background-color: #ffffff;
  --text-color: #000000;
  --primary-color: #4CAF50;
}

body {
  background-color: var(--background-color);
  color: var(--text-color);
}

button {
  background-color: var(--primary-color);
  color: var(--text-color);
}

This sets up basic light mode styles using CSS variables. The :root selector defines the global variables, and elements use var(--variable-name) to apply those values.

Dark Mode Styles:

For dark mode, create a separate class (e.g., .dark-mode) that changes the values of these variables.

.dark-mode {
  --background-color: #121212;
  --text-color: #ffffff;
  --primary-color: #BB86FC;
}

In dark mode, the background turns dark, the text becomes light, and the primary color changes to a more muted tone.

Step 2: Create the HTML Structure

Now, let's add a basic HTML structure for your website, including a dark mode toggle button.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dark Mode Example</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <header>
    <h1>Dark Mode Implementation</h1>
    <button id="toggle-dark-mode">Toggle Dark Mode</button>
  </header>
  <main>
    <p>This is an example of how to implement dark mode on a website.</p>
  </main>
  <script src="script.js"></script>
</body>
</html>

The button with the ID toggle-dark-mode will be used to trigger dark mode when clicked. This simple HTML structure includes a heading and some text content.

Step 3: Add JavaScript to Toggle Dark Mode

Next, you'll use JavaScript to toggle between light and dark mode by adding or removing the .dark-mode class to the <body> element.

JavaScript for the Toggle Button:

const toggleButton = document.getElementById('toggle-dark-mode');
const body = document.body;

toggleButton.addEventListener('click', () => {
  body.classList.toggle('dark-mode');
});

This script listens for a click on the toggle button, and when clicked, it toggles the .dark-mode class on the <body> element. When the .dark-mode class is added, the dark mode styles will be applied; when removed, the light mode styles will take over.

Step 4: Save User Preferences with Local Storage

To ensure the user's dark mode preference persists across page reloads, you can store the selection in the browser’s localStorage. Update the JavaScript code to check for this preference and apply it when the page loads.

Updated JavaScript with Local Storage:

const toggleButton = document.getElementById('toggle-dark-mode');
const body = document.body;

// Check if dark mode was previously enabled
const isDarkMode = localStorage.getItem('darkMode') === 'enabled';

if (isDarkMode) {
  body.classList.add('dark-mode');
}

toggleButton.addEventListener('click', () => {
  body.classList.toggle('dark-mode');

  if (body.classList.contains('dark-mode')) {
    localStorage.setItem('darkMode', 'enabled');
  } else {
    localStorage.setItem('darkMode', 'disabled');
  }
});

With this code, the site checks if darkMode is enabled when the page loads. If it is, dark mode is automatically applied. When the user toggles dark mode, their preference is saved in localStorage as either enabled or disabled.

Step 5: Test and Refine

Now that you’ve implemented dark mode, test your site across different browsers and devices to ensure compatibility. Make sure all elements on your website (buttons, text, backgrounds) look good in both light and dark modes.

You can refine the styles by customizing the color scheme for dark mode or applying different transitions for a smoother experience when switching between modes.

Example of Smooth Transitions:

body {
  transition: background-color 0.3s, color 0.3s;
}

Adding transitions ensures that the background and text colors change smoothly when toggling between light and dark modes, improving the user experience.

Conclusion

Implementing dark mode on your website is a great way to enhance accessibility and user satisfaction. By using CSS custom properties and a simple JavaScript toggle, you can easily switch between light and dark themes. For a more polished experience, remember to save the user's preferences using localStorage and test your implementation across different devices.