forked from xplshn/AppBundleHUB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
darkMode.js
33 lines (29 loc) · 1.17 KB
/
darkMode.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
document.addEventListener('DOMContentLoaded', () => {
const themeToggle = document.querySelector('.theme-controller');
const navElement = document.querySelector('nav');
// Function to apply the theme
const applyTheme = (theme) => {
document.body.setAttribute('data-theme', theme);
if (navElement) {
navElement.setAttribute('data-theme', theme);
}
if (themeToggle) {
themeToggle.checked = theme === 'dark';
}
};
// Detect user's preferred color scheme
const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)').matches;
const storedTheme = localStorage.getItem('theme');
const defaultTheme = storedTheme || (prefersDarkScheme ? 'dark' : 'light');
// Apply the detected/stored theme
applyTheme(defaultTheme);
// Handle theme toggle changes
if (themeToggle) {
themeToggle.addEventListener('change', (e) => {
const isDarkMode = e.target.checked;
const newTheme = isDarkMode ? 'dark' : 'light';
applyTheme(newTheme);
localStorage.setItem('theme', newTheme); // Save the user's preference
});
}
});