Table of Contents
Implementing dark mode in websites enhances user experience by reducing eye strain and providing a modern look. To make dark mode persistent across page reloads, developers often use local storage combined with CSS variables. This approach ensures that users’ preferences are saved and automatically applied whenever they revisit the site.
Understanding the Basics
CSS variables, also known as custom properties, allow for dynamic theming. By defining color variables, you can easily switch themes by updating these variables. Local storage, on the other hand, is a browser feature that stores data on the user’s device, persisting even after the browser is closed.
Setting Up CSS Variables for Dark Mode
First, define CSS variables in the :root selector for both light and dark themes. For example:
:root {
--background-color: #ffffff;
--text-color: #000000;
}
body.dark-mode {
--background-color: #121212;
--text-color: #ffffff;
}
These variables control the background and text colors. Applying the .dark-mode class switches the theme.
Implementing the JavaScript Logic
Next, add JavaScript to toggle dark mode and save the preference in local storage:
const toggleButton = document.getElementById('darkModeToggle');
function applyTheme(isDark) {
if (isDark) {
document.body.classList.add('dark-mode');
} else {
document.body.classList.remove('dark-mode');
}
}
function savePreference(isDark) {
localStorage.setItem('darkMode', isDark);
}
function loadPreference() {
const preference = localStorage.getItem('darkMode');
if (preference === 'true') {
applyTheme(true);
} else {
applyTheme(false);
}
}
toggleButton.addEventListener('click', () => {
const isDark = !document.body.classList.contains('dark-mode');
applyTheme(isDark);
savePreference(isDark);
});
window.addEventListener('DOMContentLoaded', loadPreference);
Adding the Toggle Button
Finally, include a button in your HTML to allow users to switch themes: