Dark mode is a practical feature that can reduce eye strain and make browsing more comfortable. In this post, I’ll show you how to create a simple dark mode toggle using vanilla JavaScript and browser storage. It’s quick, efficient, and enhances user experience by remembering their preferences.
// Select the <html> element
const htmlElement = document.documentElement;
// Access localStorage for theme preference
const localStorage = window.localStorage;
let storedTheme = localStorage.getItem('theme');
let currentTheme = htmlElement.getAttribute('data-theme');
// Set theme based on system preference if no theme is stored
if (!storedTheme && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
htmlElement.setAttribute('data-theme', 'dark');
localStorage.setItem('theme', 'dark');
}
// Apply stored theme if available
if (storedTheme) {
htmlElement.setAttribute('data-theme', storedTheme);
}
// Toggle theme on button click and save preference to localStorage
document.querySelector('.theme-switcher button').addEventListener('click', () => {
currentTheme = htmlElement.getAttribute('data-theme');
const newTheme = (currentTheme === 'dark') ? 'light' : 'dark';
htmlElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
});
To use this dark mode toggle, add a toggle button and utilize the CSS classes.
<div class="theme-switcher">
<button>Toggle Dark Mode</button>
</div>
[data-theme="light"] {
background-color: white;
color: black;
}
[data-theme="dark"] {
background-color: black;
color: white;
}
And there you have it! A quick and easy way to add a dark mode toggle that remembers your users’ choices for a smoother browsing experience.