-
Notifications
You must be signed in to change notification settings - Fork 0
/
color-scheme-toggle.js
33 lines (29 loc) · 985 Bytes
/
color-scheme-toggle.js
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
const toggleButton = document.getElementById('color-scheme-toggle');
const themeTextMap = {
'dark': '☾ Dark Mode',
'light': '☀ Light Mode',
'system': '🖥 System Theme',
}
let currentTheme = null;
initTheme();
toggleButton.addEventListener('click', () => {
doToggle();
});
function doToggle() {
const themeKeys = Object.keys(themeTextMap)
currentTheme = themeKeys[(themeKeys.indexOf(currentTheme) + 1) % themeKeys.length];
localStorage.setItem('savedColorScheme', currentTheme)
applyTheme();
}
function initTheme() {
currentTheme = localStorage.getItem('savedColorScheme') || 'system';
applyTheme()
}
function applyTheme() {
let dataTheme = currentTheme
if (dataTheme === 'system') {
dataTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? 'dark' : 'light';
}
document.documentElement.setAttribute('data-theme', dataTheme);
toggleButton.innerHTML = themeTextMap[currentTheme];
}