-
Notifications
You must be signed in to change notification settings - Fork 202
/
darkMode.js
41 lines (36 loc) · 1.54 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
40
41
// Theme switcher functionality
document.addEventListener('DOMContentLoaded', () => {
const themeToggle = document.querySelector('#checkbox');
const modeLabel = document.querySelector('#mode-label');
// Check for saved theme preference
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
document.body.classList.toggle('dark-theme', savedTheme === 'dark');
themeToggle.checked = savedTheme === 'dark';
modeLabel.textContent = savedTheme === 'dark' ? 'Dark Mode' : 'Light Mode';
}
// Theme toggle handler
themeToggle.addEventListener('change', (e) => {
if (e.target.checked) {
document.body.classList.add('dark-theme');
localStorage.setItem('theme', 'dark');
modeLabel.textContent = 'Dark Mode';
} else {
document.body.classList.remove('dark-theme');
localStorage.setItem('theme', 'light');
modeLabel.textContent = 'Light Mode';
}
});
// Optional: Add system theme preference detection
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
function setThemeBySystemPreference(e) {
if (!localStorage.getItem('theme')) {
const isDark = e.matches;
document.body.classList.toggle('dark-theme', isDark);
themeToggle.checked = isDark;
modeLabel.textContent = isDark ? 'Dark Mode' : 'Light Mode';
}
}
prefersDark.addListener(setThemeBySystemPreference);
setThemeBySystemPreference(prefersDark);
});