-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdark-mode.js
More file actions
47 lines (42 loc) · 1.54 KB
/
dark-mode.js
File metadata and controls
47 lines (42 loc) · 1.54 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
38
39
40
41
42
43
44
45
46
47
(function(){
const storageKey = 'theme';
const root = document.documentElement;
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
function applyTheme(theme) {
if (theme === 'dark') root.classList.add('dark');
else root.classList.remove('dark');
const btn = document.getElementById('themeToggle');
if (btn) btn.textContent = theme === 'dark' ? '☀️' : '🌙';
}
const saved = localStorage.getItem(storageKey);
let theme = saved || (prefersDark ? 'dark' : 'light');
applyTheme(theme);
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById('themeToggle');
if (btn) {
btn.addEventListener('click', () => {
theme = root.classList.contains('dark') ? 'light' : 'dark';
applyTheme(theme);
localStorage.setItem(storageKey, theme);
});
}
// If user has no saved preference, respond to system changes
if (!saved && window.matchMedia) {
try {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
const newPref = e.matches ? 'dark' : 'light';
applyTheme(newPref);
});
} catch (e) {
// some browsers use removeListener/addListener fallback
const mq = window.matchMedia('(prefers-color-scheme: dark)');
if (mq.addListener) {
mq.addListener((e) => {
const newPref = e.matches ? 'dark' : 'light';
applyTheme(newPref);
});
}
}
}
});
})();