website2/scripts/main.js
2023-08-06 15:10:13 +02:00

95 lines
2.7 KiB
JavaScript

const theme_switcher = document.getElementById("theme-switcher");
const imgs = document.getElementsByTagName("img");
const sections_button = document.getElementById("sections-button");
const sections_menu = document.getElementsByTagName("nav")[0];
const main = document.getElementsByTagName("main")[0];
let theme = window.localStorage.getItem("theme");
if (theme !== null) {
if (theme === "light") {
changeToLightTheme();
} else {
changeToDarkTheme();
}
} else {
if (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
changeToDarkTheme();
}
}
theme_switcher.addEventListener("click", () => {
const attribute = theme_switcher.getAttribute("title") ?? "off"
if (attribute.indexOf("off") !== -1) {
changeToDarkTheme();
} else {
changeToLightTheme();
}
});
function changeToDarkTheme() {
theme_switcher?.setAttribute("title", "turn the light on");
document.documentElement.style.setProperty("--border", "var(--dark-border)");
document.documentElement.style.setProperty("--text", "var(--dark-text)");
document.documentElement.style.setProperty("--bg", "var(--dark-bg)");
window.localStorage.setItem("theme", "dark");
for (let i = 0; i < imgs.length; i += 1) {
imgs[i].src = imgs[i].src.replace("-light", "-dark");
}
}
function changeToLightTheme() {
theme_switcher?.setAttribute("title", "turn the light off");
document.documentElement.style.setProperty("--border", "var(--light-border)");
document.documentElement.style.setProperty("--text", "var(--light-text)");
document.documentElement.style.setProperty("--bg", "var(--light-bg)");
window.localStorage.setItem("theme", "light");
for (let i = 0; i < imgs.length; i += 1) {
imgs[i].src = imgs[i].src.replace("-dark", "-light");
}
}
function closeMenu() {
sections_button.setAttribute("opened", "false");
sections_button.children[0].src = sections_button.children[0].src.replace(
"opened",
"closed",
);
sections_menu.style.display = "none";
}
function openMenu() {
sections_button.setAttribute("opened", "true");
sections_button.children[0].src = sections_button.children[0].src.replace(
"closed",
"opened",
);
sections_menu.style.display = "flex";
sections_menu.style.flexDirection = "column";
}
sections_button.addEventListener("click", () => {
if (sections_button.getAttribute("opened") === "false") {
openMenu();
} else {
closeMenu();
}
});
window.addEventListener("resize", () => {
if (sections_button.getAttribute("opened") === "true") {
closeMenu();
}
});
main.addEventListener("click", () => {
if (sections_button.getAttribute("opened") === "true") {
closeMenu();
}
});