Back
Creating a Dynamic Color Toggle Button for Light and Dark Mode
A step-by-step guide to an accessible toggle button that switches between light and dark themes, follows the system setting and remembers the choice.
What this dark mode toggle does
A pill-shaped switch that moves between light and dark mode. Unlike a plain class toggle, it starts in the theme the visitor's system already uses (prefers-color-scheme), remembers the choice in localStorage, and tells screen readers whether dark mode is on. The demo above is the same code you can copy below.HTML Structure
The switch is a real<button>, so it works with Tab, Enter and Space without extra code. It has no visible text, so aria-label="Dark mode" gives it a name, and aria-pressed says whether dark mode is on. Screen readers then announce it as a toggle button, pressed or not pressed. The circle is decoration and is hidden from assistive technology. The theme text under the switch is optional.
<div class="toggle-container">
<button type="button" class="toggle-button" aria-label="Dark mode" aria-pressed="false">
<span class="toggle-circle" aria-hidden="true"></span>
</button>
</div>
<div class="theme-info">Theme: <span id="theme-name">Light</span></div>
JavaScript to Toggle Themes
applyTheme() is the single place that changes the page: it puts the dark-mode class on the <html> element, moves the switch, updates aria-pressed and the label. On load, a saved choice wins; without one, the system setting decides. Each click flips the theme and saves it. localStorage can throw when storage is blocked, so both reads and writes are wrapped in try: the toggle still works, it just is not remembered.
const root = document.documentElement;
const toggleButton = document.querySelector('.toggle-button');
const themeName = document.getElementById('theme-name');
function getSavedTheme() {
try {
return localStorage.getItem('theme');
} catch (e) {
return null; // storage blocked, e.g. some privacy modes
}
}
function applyTheme(theme) {
const isDark = theme === 'dark';
root.classList.toggle('dark-mode', isDark);
toggleButton.classList.toggle('active', isDark);
toggleButton.setAttribute('aria-pressed', String(isDark));
themeName.textContent = isDark ? 'Dark' : 'Light';
}
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
applyTheme(getSavedTheme() || (prefersDark ? 'dark' : 'light'));
toggleButton.addEventListener('click', () => {
const next = root.classList.contains('dark-mode') ? 'light' : 'dark';
applyTheme(next);
try {
localStorage.setItem('theme', next);
} catch (e) {}
});
Keep the accessible name constant ("Dark mode") and let aria-pressed carry the state. Changing the label to "Switch to light mode" and also using aria-pressed gives contradictory announcements, so pick one approach.Styling with CSS
The colors live on.dark-mode body, so the class on <html> switches the whole page. color-scheme: dark makes native parts such as scrollbars and form fields dark too. :focus-visible adds a clear outline for keyboard users, and under prefers-reduced-motion the switch and background change instantly instead of sliding.
body {
font-family: Arial, sans-serif;
transition: background-color 0.5s, color 0.5s;
background-color: #ffffff;
color: #000000;
}
.dark-mode {
color-scheme: dark;
}
.dark-mode body {
background-color: #2c2f33;
color: #ffffff;
}
.toggle-container {
display: flex;
justify-content: center;
align-items: center;
height: 50vh;
}
.toggle-button {
border: 2px solid #000;
background-color: #fff;
border-radius: 30px;
width: 60px;
height: 30px;
position: relative;
cursor: pointer;
transition: background-color 0.5s, border-color 0.5s;
}
.toggle-button:focus-visible {
outline: 3px solid #4c9ffe;
outline-offset: 3px;
}
.toggle-button .toggle-circle {
background-color: #000;
border-radius: 50%;
width: 22px;
height: 22px;
position: absolute;
top: 2px;
left: 2px;
transition: left 0.5s;
}
.toggle-button.active {
background-color: #262626;
border-color: #fff;
}
.toggle-button.active .toggle-circle {
left: 32px;
background-color: #fff;
}
.theme-info {
text-align: center;
font-size: 1.2em;
margin-left: 2px;
}
@media (prefers-reduced-motion: reduce) {
body,
.toggle-button,
.toggle-button .toggle-circle {
transition: none;
}
}
Avoid the flash of the wrong theme on page load
The main script runs after the page is drawn, so a visitor who chose dark mode can see a white flash on every page load. Put a tiny inline script in<head>, before your stylesheet, that sets the class before the first paint. It must be a normal inline script, not defer or type="module". <body> does not exist yet at that point, which is why the class goes on <html>.
<head>
<script>
(function () {
var saved = null;
try { saved = localStorage.getItem('theme'); } catch (e) {}
var dark = saved ? saved === 'dark'
: window.matchMedia('(prefers-color-scheme: dark)').matches;
if (dark) document.documentElement.classList.add('dark-mode');
})();
</script>
<link rel="stylesheet" href="styles.css">
</head>
If your site has a Content Security Policy that blocks inline scripts, allow this one with its hash or a nonce.Keep several tabs in sync
Thestorage event fires in the other open tabs of your site when one tab saves a new value, so all tabs can switch together:
window.addEventListener('storage', (event) => {
if (event.key === 'theme') applyTheme(event.newValue || 'light');
});
Conclusion
This color toggle button switches between light and dark themes with a smooth slide, follows the visitor's system setting on the first visit, remembers their choice afterwards, and works with a keyboard and screen readers. Change the colors in.dark-mode body and the switch styles to fit your project.Whole code
<div class="toggle-container">
<button type="button" class="toggle-button" aria-label="Dark mode" aria-pressed="false">
<span class="toggle-circle" aria-hidden="true"></span>
</button>
</div>
<div class="theme-info">Theme: <span id="theme-name">Light</span></div>
<script>
const root = document.documentElement;
const toggleButton = document.querySelector('.toggle-button');
const themeName = document.getElementById('theme-name');
function getSavedTheme() {
try {
return localStorage.getItem('theme');
} catch (e) {
return null; // storage blocked, e.g. some privacy modes
}
}
function applyTheme(theme) {
const isDark = theme === 'dark';
root.classList.toggle('dark-mode', isDark);
toggleButton.classList.toggle('active', isDark);
toggleButton.setAttribute('aria-pressed', String(isDark));
themeName.textContent = isDark ? 'Dark' : 'Light';
}
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
applyTheme(getSavedTheme() || (prefersDark ? 'dark' : 'light'));
toggleButton.addEventListener('click', () => {
const next = root.classList.contains('dark-mode') ? 'light' : 'dark';
applyTheme(next);
try {
localStorage.setItem('theme', next);
} catch (e) {}
});
</script>
<style>
body {
font-family: Arial, sans-serif;
transition: background-color 0.5s, color 0.5s;
background-color: #ffffff;
color: #000000;
}
.dark-mode {
color-scheme: dark;
}
.dark-mode body {
background-color: #2c2f33;
color: #ffffff;
}
.toggle-container {
display: flex;
justify-content: center;
align-items: center;
height: 50vh;
}
.toggle-button {
border: 2px solid #000;
background-color: #fff;
border-radius: 30px;
width: 60px;
height: 30px;
position: relative;
cursor: pointer;
transition: background-color 0.5s, border-color 0.5s;
}
.toggle-button:focus-visible {
outline: 3px solid #4c9ffe;
outline-offset: 3px;
}
.toggle-button .toggle-circle {
background-color: #000;
border-radius: 50%;
width: 22px;
height: 22px;
position: absolute;
top: 2px;
left: 2px;
transition: left 0.5s;
}
.toggle-button.active {
background-color: #262626;
border-color: #fff;
}
.toggle-button.active .toggle-circle {
left: 32px;
background-color: #fff;
}
.theme-info {
text-align: center;
font-size: 1.2em;
margin-left: 2px;
}
@media (prefers-reduced-motion: reduce) {
body,
.toggle-button,
.toggle-button .toggle-circle {
transition: none;
}
}
</style>
Thank you for reading this article.
Comments