Skip to content

Instantly share code, notes, and snippets.

@adamstallard
Last active January 11, 2025 00:13
Show Gist options
  • Select an option

  • Save adamstallard/c040ab919adaec9cbe4e923aa655db35 to your computer and use it in GitHub Desktop.

Select an option

Save adamstallard/c040ab919adaec9cbe4e923aa655db35 to your computer and use it in GitHub Desktop.
Dark mode switch Lit
@state()
private _isDarkMode = this._getInitialTheme();
private _getInitialTheme(): boolean {
const storedTheme = localStorage.getItem('theme');
if (storedTheme) {
return storedTheme === 'dark';
} else {
return window.matchMedia('(prefers-color-scheme: dark)').matches;
}
}
connectedCallback() {
super.connectedCallback();
this._applyTheme();
}
private _toggleTheme() {
this._isDarkMode = !this._isDarkMode;
localStorage.setItem('theme', this._isDarkMode ? 'dark' : 'light');
this._applyTheme();
}
private _applyTheme() {
if (this._isDarkMode) {
document.documentElement.classList.add('dark-theme');
} else {
document.documentElement.classList.remove('dark-theme');
}
}
:root.dark-theme {
--bg-color: #121212;
--text-color: #eeeeee;
--primary-color: #0b5ed7;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment