-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme.js
More file actions
38 lines (34 loc) · 1.12 KB
/
Copy paththeme.js
File metadata and controls
38 lines (34 loc) · 1.12 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
function getPreferredTheme() {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'light' || savedTheme === 'dark') {
return savedTheme;
}
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function applyTheme(theme) {
const root = document.documentElement;
const button = document.querySelector('.theme-toggle-btn');
if (theme === 'dark') {
root.setAttribute('data-theme', 'dark');
if (button) {
button.innerHTML = '<i class="fa-solid fa-sun" aria-hidden="true"></i>';
}
} else {
root.removeAttribute('data-theme');
if (button) {
button.innerHTML = '<i class="fa-solid fa-moon" aria-hidden="true"></i>';
}
}
}
function toggleTheme() {
const nextTheme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
localStorage.setItem('theme', nextTheme);
applyTheme(nextTheme);
}
document.addEventListener('DOMContentLoaded', () => {
applyTheme(getPreferredTheme());
const button = document.querySelector('.theme-toggle-btn');
if (button) {
button.addEventListener('click', toggleTheme);
}
});