-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme-toggle.js
More file actions
59 lines (52 loc) · 2.38 KB
/
Copy paththeme-toggle.js
File metadata and controls
59 lines (52 loc) · 2.38 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const themeLinks = document.querySelectorAll('.theme-toggle-dropdown-content a');
const themeToggleDiv = document.querySelector('.theme-toggle');
const themeDropdown = document.querySelector('.theme-toggle-dropdown');
const themeIcon = document.getElementById('theme-icon'); // Dropdown button icon
// Listen for clicks on the theme change options
themeLinks.forEach(link => {
link.addEventListener('click', (event) => {
// Prevent the link from navigating
event.preventDefault();
const selectedTheme = link.getAttribute('data-theme'); // Get the data-theme attribute from the clicked <a>
if (selectedTheme) {
applyTheme(selectedTheme); // Apply the selected theme
localStorage.setItem('theme', selectedTheme); // Store it in localStorage
}
});
});
// Toggle dropdown visibility when the button is clicked
themeDropdown.addEventListener('click', (event) => {
event.stopPropagation(); // Prevent the click event from propagating
themeDropdown.classList.toggle('open'); // Toggle dropdown visibility
});
// Close the dropdown if clicked outside of it
document.addEventListener('click', (event) => {
if (!themeDropdown.contains(event.target)) {
themeDropdown.classList.remove('open');
}
});
function applyTheme(theme) {
// Update the theme and button icon based on selection
if (theme === 'auto') {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.setAttribute('data-theme', prefersDark ? 'dark' : 'light');
themeIcon.className = 'fa-solid fa-circle-half-stroke'; // Change icon for auto
} else if (theme === 'light') {
document.documentElement.setAttribute('data-theme', 'light');
themeIcon.className = 'fa-solid fa-sun'; // Change icon for light
} else if (theme === 'dark') {
document.documentElement.setAttribute('data-theme', 'dark');
themeIcon.className = 'fa-solid fa-moon'; // Change icon for dark
}
}
// Apply saved theme on page load
const savedTheme = localStorage.getItem('theme') || 'auto';
applyTheme(savedTheme);
// Scroll Hide Logic - Hide button when scrolling
window.addEventListener('scroll', () => {
if (window.scrollY > 0) {
themeToggleDiv.classList.add('hidden'); // Hide the toggle button when scrolling
} else {
themeToggleDiv.classList.remove('hidden'); // Show the button when at the top
}
});