Implementing Dark Mode Toggle with Css Variables and Javascript

Implementing a dark mode toggle on a website enhances user experience by allowing visitors to switch between light and dark themes. Using CSS variables combined with JavaScript provides a flexible and efficient way to achieve this feature. In this article, we will explore how to implement a dark mode toggle using these technologies.

Understanding CSS Variables

CSS variables, also known as custom properties, allow you to define reusable values that can be changed dynamically. They are declared within a :root selector for global scope or within specific selectors for scoped styles. For dark mode, we typically define variables for colors, backgrounds, and text styles.

Example of defining CSS variables:

:root {
  --background-color: #ffffff;
  --text-color: #000000;
}
.dark-mode {
  --background-color: #121212;
  --text-color: #ffffff;
}

Implementing the Toggle Button

Adding a toggle button in your HTML allows users to switch themes. You can place this button anywhere suitable in your layout, such as in the header or a sidebar.

Example button:

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

JavaScript Functionality

Using JavaScript, we listen for click events on the toggle button. When clicked, we toggle a class on the <body> element, which switches between light and dark modes by changing CSS variables.

Example script:

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

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

Applying CSS Styles

Finally, style your page using the CSS variables. Use them for background and text colors to automatically update when the theme switches.

body {
  background-color: var(--background-color);
  color: var(--text-color);
  transition: background-color 0.3s, color 0.3s;
}

Now, when users click the toggle button, the theme will switch smoothly between light and dark modes, enhancing accessibility and user comfort.