Javascript: localStorage and the string format
While I was programming the lunar phase article, I ran into a
problem with localStorage.
For those who don't know, localStorage is an area where you can store the data inside the browser. It works
like cookies somewhat, but cookies are not necessary for this technology.
// Store a key called "key1" which has a certain "value" in string format. localStorage.setItem("key1", "value"); // Store the string value "true" or "false" of a checkbox. localStorage.setItem("key2", document.getElementById("my_checkbox").checked); // Get a value. PLEASE NOTE: it's a string! localStorage.getItem("key2"); // Convert a string to a boolean let myboolean = (localStorage.getItem("key2") === "true" ? true : false); if (myboolean) { // TODO } else { // TODO }
As you can see from the examples above, using localStorage is easy. However, you need to consider that localStorage is always stored as a string. If you want to store a boolean, you need to do a test (with a ternary) for obtaining a boolean value.
In the lunar phase article I used localStorage for saving which hemisphere the user has set (Northern or Southern). You need to activate functional cookies for that. By the way, cookies are not tied to localStorage.
2023
Dec, 16
Dec, 16