forked from opengaming/osgameclones
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dark-theme.js
59 lines (53 loc) · 1.77 KB
/
dark-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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const DARK_THEME_CLASS = 'dark-theme';
const LIGHT_THEME_CLASS = 'light-theme';
const DARK_THEME_KEY = 'startInDarkTheme';
function setDarkTheme() {
document.body.classList.remove(LIGHT_THEME_CLASS);
document.body.classList.add(DARK_THEME_CLASS);
setThemeButtonText("Light Theme");
}
function setLightTheme() {
document.body.classList.remove(DARK_THEME_CLASS);
document.body.classList.add(LIGHT_THEME_CLASS);
setThemeButtonText("Dark Theme");
}
function toggleDarkTheme() {
if (document.body.classList.contains(DARK_THEME_CLASS)) {
setLightTheme();
localStorage.setItem(DARK_THEME_KEY, 'false')
} else {
setDarkTheme();
localStorage.setItem(DARK_THEME_KEY, 'true')
}
}
/**
* Safely modify theme button text only if it exists
* @param {string} text label for button
*/
function setThemeButtonText(text) {
const button = document.getElementById('dark-theme-button')
if (button) {
button.innerHTML = text
}
}
// enable dark theme as soon as possible so first paint is already dark mode
(function () {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
if (localStorage.getItem(DARK_THEME_KEY) === null) {
if (event.matches) {
setDarkTheme();
} else {
setLightTheme();
}
}
});
if (localStorage.getItem(DARK_THEME_KEY) === 'true' || window.matchMedia('(prefers-color-scheme: dark)').matches) {
setDarkTheme();
}
})();
// handle theme button label and listener once DOM fully loaded
window.addEventListener('DOMContentLoaded', function () {
const isDarkTheme = document.body.classList.contains(DARK_THEME_CLASS)
setThemeButtonText(isDarkTheme ? "Light Theme" : "Dark Theme")
document.getElementById('dark-theme-button').addEventListener('click', toggleDarkTheme)
})