I would like to allow visitors who don't have dark mode enabled on their device or browser a one-click option to enable it.
How do I fetch current cookie, change it, and then reset it before early in the loading stage of the site?
const currentScheme = () => {
var colorScheme = "";
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
colorScheme = "dark";
}
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
colorScheme = e.matches ? "dark" : "light";
if(colorScheme !== "dark") {
if(document.body.classList.contains("global-hash-dark-version")) {
document.body.classList.remove("global-hash-dark-version");
}
} else {
if(!document.body.classList.contains("global-hash-dark-version")) {
document.body.classList.add("global-hash-dark-version");
}
}
})
return colorScheme;
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
let cookieValue = getCookie("choice_settings");
if(cookieValue) {
let currentSettings = JSON.parse(cookieValue);
if (currentSettings.colorScheme == "dark") {
document.body.classList.add("global-hash-dark-version");
console.log("dark")
}
} else {
const temp_scheme = currentScheme();
if (temp_scheme == "dark") {
currentSettings = {
colorScheme: "dark",
...currentSettings
}
// This is where I am stuck.
// How do I fetch, update, and then reset the cookie with settings?
// Other settings will be things like privacy consent and dismissed
// notifications
//
//
}