-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
45 lines (39 loc) · 1.66 KB
/
script.js
File metadata and controls
45 lines (39 loc) · 1.66 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
document.addEventListener('DOMContentLoaded', () => {
const themeToggle = document.getElementById('theme-toggle');
const root = document.documentElement;
const toggleIcon = themeToggle.querySelector('.toggle-icon');
const toggleText = themeToggle.querySelector('.toggle-text');
// Utility to get current applied theme
const getCurrentTheme = () => {
const savedTheme = localStorage.getItem('theme');
if (savedTheme) return savedTheme;
return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
};
// Update the button UI based on the theme
const updateToggleUI = (theme) => {
const isLight = theme === 'light';
toggleIcon.textContent = isLight ? '🌙' : '☀️';
toggleText.textContent = isLight ? 'Dark Mode' : 'Light Mode';
};
// Initial setup
const initialTheme = getCurrentTheme();
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
root.setAttribute('data-theme', savedTheme);
}
updateToggleUI(initialTheme);
// Listen for manual toggle
themeToggle.addEventListener('click', () => {
const currentTheme = getCurrentTheme();
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
root.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateToggleUI(newTheme);
});
// Listen for system preference changes
window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', (e) => {
if (!localStorage.getItem('theme')) {
updateToggleUI(e.matches ? 'light' : 'dark');
}
});
});