-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme.js
More file actions
37 lines (31 loc) · 1.04 KB
/
theme.js
File metadata and controls
37 lines (31 loc) · 1.04 KB
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
37
const themeToggle = document.getElementById('themeToggle');
const root = document.documentElement;
const themeStorageKey = 'theme';
const getSystemTheme = () =>
window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
const updateToggleLabel = (theme) => {
if (!themeToggle) {
return;
}
themeToggle.textContent = theme === 'dark' ? 'Light mode' : 'Dark mode';
};
const applyTheme = (theme) => {
root.dataset.theme = theme;
updateToggleLabel(theme);
};
const storedTheme = localStorage.getItem(themeStorageKey);
applyTheme(storedTheme || getSystemTheme());
if (themeToggle) {
themeToggle.addEventListener('click', () => {
const nextTheme = root.dataset.theme === 'dark' ? 'light' : 'dark';
localStorage.setItem(themeStorageKey, nextTheme);
applyTheme(nextTheme);
});
}
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
mediaQuery.addEventListener('change', (event) => {
if (localStorage.getItem(themeStorageKey)) {
return;
}
applyTheme(event.matches ? 'dark' : 'light');
});