feat: better dark mode switch

This commit is contained in:
grassblock 2025-05-03 18:04:08 +08:00
parent d5f81c0f81
commit 1da8ae56c4
2 changed files with 57 additions and 10 deletions

View file

@ -5,18 +5,38 @@
</button>
<script>
// Inspired by https://blog.skk.moe/post/hello-darkmode-my-old-friend/
const themeSwitcher = document.getElementById('theme-switcher');
const root = document.documentElement;
const preferredTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? 'dark' : 'light'
// Check for saved theme preference or default to dark
const savedTheme = localStorage.getItem('theme') || 'dark';
root.setAttribute('data-theme', savedTheme);
const savedTheme = localStorage.getItem('theme');
// If the saved theme is the same as the system preferred theme, set it and remove it from localStorage
if (savedTheme === preferredTheme) {
root.removeAttribute('data-theme');
localStorage.removeItem('theme');
} else if (savedTheme) {
// Or if another saved theme is found, set it
root.setAttribute('data-theme', savedTheme);
} else {
// Or if no saved theme is found, use the system preferred theme until the theme is toggled
root.removeAttribute('data-theme');
localStorage.removeItem('theme');
}
themeSwitcher?.addEventListener('click', () => {
const currentTheme = root.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
root.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
// get current theme from localStorage
const currentTheme = localStorage.getItem('theme');
// check if the current theme is correctly set, toggles it and saves it to localStorage
if (currentTheme !== null && ['dark', 'light'].includes(currentTheme)) {
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
root.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
} else {
// if not set, toggle from the system preferred theme and save it to localStorage
const newTheme = preferredTheme === 'dark' ? 'light' : 'dark';
root.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
}
});
</script>