The theme switcher is a customized select element with a small script to control your theme modes.

Technical Details

  • The script switches the data-theme-mode attribute on the html (and theme switcher) element to identify the selected theme.
  • You have to set up an additional color theme.

Theme Detection

The JS code above only handles the switch and its states. You also have to detect a default or chosen theme. For this, you can use matchMedia with prefers-color-scheme: dark;. You MUST embed this script inline in your header as far ahead as possible.

javascript
(() => {
const darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
const preferredTheme = localStorage.getItem('preferred-theme');
function setTheme(theme) {
if (theme === 'dark') {
document.documentElement.setAttribute('data-theme-mode', 'dark');
} else if (theme === 'system' && darkQuery.matches) {
document.documentElement.setAttribute('data-theme-mode', 'dark');
} else {
document.documentElement.removeAttribute('data-theme-mode');
}
}
setTheme(preferredTheme || (darkQuery.matches ? 'dark' : 'light'));
})();

Resources

  • Icons: 1, 2, 3