You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.9 KiB
58 lines
1.9 KiB
function load() {
|
|
// setting the ID for the buttons used for toggling.
|
|
// in order to support multiple buttons, e.g. to support collapsing navbars for mobile devices we create an array
|
|
const buttons = document.querySelectorAll(".themebtn");
|
|
|
|
// Get the stored value for the session
|
|
function getStoredUseDark() {
|
|
const storedUseDark = sessionStorage.getItem("useDark");
|
|
if (storedUseDark != null){
|
|
return (storedUseDark == "true");
|
|
}
|
|
}
|
|
|
|
// Set the stored value for the session
|
|
function setStoredUseDark(storeValue){
|
|
const storeStringValue = ((storeValue == true) ? "true" : "false");
|
|
sessionStorage.setItem("useDark",storeStringValue);
|
|
}
|
|
|
|
// MediaQueryList object
|
|
const useDark = window.matchMedia("(prefers-color-scheme: dark)");
|
|
|
|
// Toggles the "dark-mode" class based on if the media query matches
|
|
function toggleDarkMode(state) {
|
|
// Older browser don't support the second parameter in the
|
|
// classList.toggle method so you'd need to handle this manually
|
|
// if you need to support older browsers.
|
|
document.documentElement.classList.toggle("dark-mode", state);
|
|
setStoredUseDark(state);
|
|
}
|
|
|
|
// Initial setting of the preffered system setting
|
|
function initialization(){
|
|
const initUseDark = getStoredUseDark();
|
|
if (initUseDark != true && initUseDark != false){
|
|
toggleDarkMode(useDark.matches);
|
|
}else{
|
|
toggleDarkMode(initUseDark);
|
|
}
|
|
}
|
|
|
|
initialization();
|
|
|
|
// Listen for changes in the OS settings
|
|
useDark.addListener((evt) => toggleDarkMode(evt.matches));
|
|
|
|
// Toggles the "dark-mode" class on click
|
|
// We itterate over each button in the buttons array:
|
|
buttons.forEach(button => {
|
|
button.addEventListener("click", () => {
|
|
const toggledStoredUseDark = (getStoredUseDark() ? false : true);
|
|
toggleDarkMode(toggledStoredUseDark);
|
|
});
|
|
});
|
|
}
|
|
|
|
window.addEventListener("DOMContentLoaded", load);
|
|
|