Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d9a77ab

Browse files
committed
New: Color theme script added.
1 parent 9b28fe7 commit d9a77ab

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

‎dom/color_theme.html

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<script>
2+
// Theme switcher
3+
4+
let themeSwitcher = document.getElementById('themeSwitcher');
5+
6+
const getPreferredTheme = () => {
7+
if (localStorage.getItem('theme') != null) {
8+
return localStorage.getItem('theme');
9+
}
10+
11+
return document.documentElement.dataset.theme;
12+
};
13+
14+
const setTheme = function (theme) {
15+
if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
16+
document.documentElement.dataset.theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
17+
} else {
18+
document.documentElement.dataset.theme = theme;
19+
}
20+
21+
localStorage.setItem('theme', theme);
22+
};
23+
24+
const showActiveTheme = theme => {
25+
const activeBtn = document.querySelector(`[data-theme-value="${theme}"]`);
26+
27+
document.querySelectorAll('[data-theme-value]').forEach(element => {
28+
element.classList.remove('active');
29+
});
30+
31+
activeBtn && activeBtn.classList.add('active');
32+
33+
// Set button if demo mode is enabled
34+
document.querySelectorAll('[data-theme-control="theme"]').forEach(element => {
35+
if (element.value == theme) {
36+
element.checked = true;
37+
}
38+
});
39+
};
40+
41+
function reloadPage() {
42+
window.location = window.location.pathname;
43+
}
44+
45+
46+
setTheme(getPreferredTheme());
47+
48+
if(typeof themeSwitcher != 'undefined') {
49+
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
50+
if(localStorage.getItem('theme') != null) {
51+
if (localStorage.getItem('theme') == 'auto') {
52+
reloadPage();
53+
}
54+
}
55+
});
56+
57+
window.addEventListener('load', () => {
58+
showActiveTheme(getPreferredTheme());
59+
60+
document.querySelectorAll('[data-theme-value]').forEach(element => {
61+
element.addEventListener('click', () => {
62+
const theme = element.getAttribute('data-theme-value');
63+
64+
localStorage.setItem('theme', theme);
65+
reloadPage();
66+
})
67+
})
68+
});
69+
}
70+
</script>
71+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /