Color Toggle Mode
Color Toggle Mode is coded from ShadCN UI and Docusaurus.
function getThemePreference(): 'light' | 'dark' {
// Check localStorage first
if (typeof localStorage !== 'undefined') {
const storedTheme = localStorage.getItem('theme');
if (storedTheme) {
return storedTheme;
}
}
// Fallback to system preference
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
// Apply initial theme
const initialTheme = getThemePreference();
document.documentElement.setAttribute('data-theme', initialTheme);
// Observe attribute changes and update localStorage
if (typeof localStorage !== 'undefined') {
const observer = new MutationObserver(() => {
const theme = document.documentElement.getAttribute('data-theme');
if (theme) {
localStorage.setItem('theme', theme);
}
});
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
window.addEventListener('storage', function (event) {
if (event.key === 'theme') {
document.documentElement.setAttribute('data-theme', event.newValue || 'light');
}
});
}
function toggleModeButton($element: HTMLButtonElement | null): void {
if (!$element) return; // Guard clause in case the button doesn't exist
$element.addEventListener('click', function (): void {
const theme = document.documentElement.getAttribute('data-theme');
const isDarkMode: boolean = theme === 'dark';
// Toggle between light and dark
document.documentElement.setAttribute('data-theme', isDarkMode ? 'light' : 'dark');
});
}
Usage
toggleModeButton(document.querySelector('#toggleButton'));