-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy paththeme.js
33 lines (27 loc) · 1.11 KB
/
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
// Get the theme toggle input
const themeToggle = document.querySelector(
'.theme-switch input[type="checkbox"]'
);
// Get the current theme from local storage
const currentTheme = localStorage.getItem("theme");
// If the current local storage item can be found
if (currentTheme) {
// Set the body data-theme attribute to match the local storage item
document.documentElement.setAttribute("data-theme", currentTheme);
// If the current theme is light, check the theme toggle
if (currentTheme === "light") {
themeToggle.checked = true;
}
}
// Function that will switch the theme based on the if the theme toggle is checked or not
function switchTheme(e) {
if (e.target.checked) {
document.documentElement.setAttribute("data-theme", "light");
localStorage.setItem("theme", "light");
} else {
document.documentElement.setAttribute("data-theme", "dark");
localStorage.setItem("theme", "dark");
}
}
// Add an event listener to the theme toggle, which will switch the theme
themeToggle.addEventListener("change", switchTheme, false);