forked from ANSHIKA-26/WordWise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
darkMode.js
39 lines (33 loc) · 1.5 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
34
35
36
37
38
39
const checkbox = document.getElementById('checkbox');
const modeLabel = document.getElementById('mode-label');
// Function to apply the theme and update the label
const applyTheme = (theme) => {
console.log(`Applying theme: ${theme}`); // Debugging line
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
checkbox.checked = (theme === 'dark');
// Update the label text based on the current theme
modeLabel.textContent = theme === 'dark' ? '' : '';
};
// Check for saved theme in localStorage or use system preference
const savedTheme = localStorage.getItem('theme');
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (savedTheme) {
console.log(`Found saved theme: ${savedTheme}`); // Debugging line
applyTheme(savedTheme);
} else {
console.log(`Using system preference: ${systemPrefersDark ? 'dark' : 'light'}`); // Debugging line
applyTheme(systemPrefersDark ? 'dark' : 'light');
}
// Add event listener for toggle switch
checkbox.addEventListener('change', () => {
const newTheme = checkbox.checked ? 'dark' : 'light';
console.log(`Checkbox changed: ${newTheme}`); // Debugging line
applyTheme(newTheme);
});
// Listen for system theme changes
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (event) => {
const newTheme = event.matches ? 'dark' : 'light';
console.log(`System theme changed: ${newTheme}`); // Debugging line
applyTheme(newTheme);
});