-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeme.js
38 lines (30 loc) · 1.33 KB
/
theme.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
function initializeTheme() {
// Check for saved theme preference or default to dark
const savedTheme = localStorage.getItem('theme') || 'dark';
document.documentElement.setAttribute('data-theme', savedTheme);
// Create and append the toggle button
const toggleButton = document.createElement('button');
toggleButton.className = 'theme-toggle';
// Use more reliable Unicode characters with fallback
const sunIcon = '☀️';
const moonIcon = '🌙';
// Set initial button text with fallback
function updateButtonText(theme) {
if (theme === 'dark') {
toggleButton.innerHTML = `${sunIcon} <span>Light</span>`;
} else {
toggleButton.innerHTML = `${moonIcon} <span>Dark</span>`;
}
}
updateButtonText(savedTheme);
toggleButton.addEventListener('click', () => {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateButtonText(newTheme);
});
document.body.appendChild(toggleButton);
}
// Initialize theme when DOM is loaded
document.addEventListener('DOMContentLoaded', initializeTheme);