-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme.js
More file actions
51 lines (44 loc) · 1.55 KB
/
theme.js
File metadata and controls
51 lines (44 loc) · 1.55 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
48
49
50
51
(function() {
const STORAGE_KEY = 'theme';
const DARK = 'dark';
const LIGHT = 'light';
function getPreferredTheme() {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
return stored;
}
return window.matchMedia('(prefers-color-scheme: light)').matches ? LIGHT : DARK;
}
function setTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem(STORAGE_KEY, theme);
updateToggleButton(theme);
}
function updateToggleButton(theme) {
const button = document.querySelector('.theme-toggle');
if (button) {
button.textContent = theme === DARK ? 'light' : 'dark';
button.setAttribute('aria-label', `Switch to ${theme === DARK ? 'light' : 'dark'} mode`);
}
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
setTheme(current === DARK ? LIGHT : DARK);
}
// Set initial theme immediately to prevent flash
setTheme(getPreferredTheme());
// Set up toggle button when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
const button = document.querySelector('.theme-toggle');
if (button) {
updateToggleButton(document.documentElement.getAttribute('data-theme'));
button.addEventListener('click', toggleTheme);
}
});
// Listen for system preference changes
window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', function(e) {
if (!localStorage.getItem(STORAGE_KEY)) {
setTheme(e.matches ? LIGHT : DARK);
}
});
})();