Javascript cookie error

I have an error with my Javascript code. I can’t toggle dark mode; isn’t working for some reason. I have tried many times to get this to work. Here’s my code:
Every page

// check for cookie
if localStorage("toggleDarkMode") {
    var element = document.body;
    element.classList.toggle("w3-dark-grey");
}
...

The settings page

// create cookie and dark mode
function toggleDarkMode() {
    var element = document.body;
    element.classList.toggle("w3-dark-grey");
    localStorage.setItem("toggleDarkMode", "w3-dark-grey");
}

I don’t see anything inherently wrong with your code, but I must admit I’ve never used local storage myself.

Do you have a web page where we can see this in action and test if we have the same issue, and check for possible issues?

2 Likes

Maybe try using

if (localStorage.getItem("toggleDarkMode") === "w3-dark-grey") {
   ...
}

instead of

if (localStorage("toggleDarkMode")) {
   ...
}

Also, your if statements need parenthesis around them.

Best check the console (F12 on most browsers) to see what’s going on.

4 Likes

If you want to keep using localStorage, do what Thewebuser said. But I noticed that you commented “check for cookie” and “create a cookie” but localStorage is not a cookie. However, setting and checking for a cookie is slightly more complicated than localStorage.

How to do it

Setting a cookie:

document.cookie = "name=value; expires=UTC String; path: /";

An example being:

let expiry = new Date();
expiry = expiry.getTime() + (365 * 24 * 60 * 60 * 1000); // A year from when it was set
document.cookie = `example=Hi; expires=${expiry.toUTCString()}; path=/`;

Getting the cookie:

function cookie(name) {
    const value = document.cookie.match(RegExp(`(?:^|;\\s*)${name}=([^;]*)`)); 
    return value ? value[1] : null;
}

Example (with cookie made previously):

function cookie(name) {
    const value = document.cookie.match(RegExp(`(?:^|;\\s*)${name}=([^;]*)`)); 
    return value ? value[1] : null;
}
console.log(cookie("example"));
// Output: Hi
3 Likes

Sure! Though, you have to login. If you want not to create an account, I’ll create a filler account and PM you the username and password.

Page is http://www.gr8brik.rf.gd/acc/index.php
Yes, I did shorten my doamin so it’s easier to read.

For some reason that didn’t work. I’ll try debugging after lunch (very soon).

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.