-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme-toggle.js
More file actions
36 lines (31 loc) · 928 Bytes
/
theme-toggle.js
File metadata and controls
36 lines (31 loc) · 928 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
(function () {
const root = document.documentElement;
const btn = document.getElementById('theme-toggle');
const storageKey = 'wsl-theme';
function getSystemPreference() {
return window.matchMedia &&
window.matchMedia('(prefers-color-scheme: light)').matches
? 'light'
: 'dark';
}
function applyTheme(theme) {
root.setAttribute('data-theme', theme);
if (btn) {
btn.textContent = theme === 'light' ? '☀️' : '🌙';
}
}
function initTheme() {
const stored = localStorage.getItem(storageKey);
const theme = stored || getSystemPreference() || 'dark';
applyTheme(theme);
}
if (btn) {
btn.addEventListener('click', () => {
const current = root.getAttribute('data-theme') || 'dark';
const next = current === 'dark' ? 'light' : 'dark';
applyTheme(next);
localStorage.setItem(storageKey, next);
});
}
initTheme();
})();