Building a Dark Mode Toggle
Implement a JavaScript toggle that adds and removes the dark class on the html element and persists the preference in localStorage.
What the Toggle Needs to Do
A dark mode toggle needs to accomplish three things: read the user's saved preference (or OS preference as a fallback), apply the correct class to the <html> element on page load, and update the class and save the preference when the user clicks the toggle button. Getting the initial load right is critical — applying the class before the page renders prevents a flash of incorrect theme.
Preventing Flash of Wrong Theme
The most common dark mode bug is a flash of light theme when a user in dark mode refreshes the page. This happens because JavaScript runs after the HTML has already been parsed and rendered. The fix is to run a tiny inline <script> in the <head> — before any CSS or body content — that reads localStorage and immediately adds the dark class if needed.
<!-- Place this FIRST inside <head> -->
<script>
if (localStorage.theme === 'dark' ||
(!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark');
}
</script>All lessons in this course
- Dark Mode Strategies
- Applying Dark Variants
- Building a Dark Mode Toggle
- Dark Mode for Complex Components