-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
92 lines (80 loc) · 2.76 KB
/
script.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Utility function to calculate the current theme setting.
* Look for a local storage value.
* Fall back to system setting.
* Fall back to light mode.
*/
function calculateSettingAsThemeString({ localStorageTheme, systemSettingDark }) {
if (localStorageTheme !== null) {
return localStorageTheme;
}
if (systemSettingDark.matches) {
return "light";
}
themeToggle.checked = true;
return "dark";
}
/**
* Utility function to update the button text and aria-label.
*/
/**
* Utility function to update the theme setting on the html tag
*/
function updateThemeOnHtmlEl({ theme }) {
document.querySelector("html").setAttribute("data-theme", theme);
}
function updateThemeToggle({ theme }) {
if (theme === "dark") {
themeToggle.checked = true;
}
}
function setTheme({ theme }) {
const styles = document.documentElement.style
if (theme === "dark") {
styles.setProperty("--theme-bg", "#121212")
styles.setProperty("--theme-color-hd", "#fff")
styles.setProperty("--theme-bg-links", "darkblue")
styles.setProperty("--theme-color-text", "#fff")
styles.setProperty("--theme-section-one-bg", "white")
styles.setProperty("--theme-programs-text", "snow")
styles.setProperty("--theme-header-bg", "#00093C")
} else {
styles.setProperty("--theme-bg", "#fff")
styles.setProperty("--theme-color-hd", "darkblue")
styles.setProperty("--theme-bg-links", "white")
styles.setProperty("--theme-color-text", "#000")
styles.setProperty("--theme-section-one-bg", "#00093C")
styles.setProperty("--theme-programs-text", "gray")
styles.setProperty("--theme-header-bg", "white")
}
}
/**
* On page load:
*/
/**
* 1. Grab what we need from the DOM and system settings on page load
*/
const themeToggle = document.getElementById("toggle");
const localStorageTheme = localStorage.getItem("theme");
const systemSettingDark = window.matchMedia("(prefers-color-scheme: dark)");
const styles = getComputedStyle(document.body)
/**
* 2. Work out the current site settings
*/
let currentThemeSetting = calculateSettingAsThemeString({ localStorageTheme, systemSettingDark });
/**
* 3. Update the theme setting and button text accoridng to current settings
*/
updateThemeOnHtmlEl({ theme: currentThemeSetting });
updateThemeToggle({theme: currentThemeSetting});
setTheme({theme: currentThemeSetting});
/**
* 4. Add an event listener to toggle the theme
*/
themeToggle.addEventListener("click", (event) => {
const newTheme = currentThemeSetting === "dark" ? "light" : "dark";
localStorage.setItem("theme", newTheme);
updateThemeOnHtmlEl({ theme: newTheme });
currentThemeSetting = newTheme;
setTheme({theme: currentThemeSetting});
});