It's pretty straightforward.
localStorage is a type of browser storage, similar to a cookie. It remembers some data so the next time a user visits a web page, that data can be used again.
It only stores strings. Usually, you see it used as a true/false state, but it can be used to store more complex types of data (like json) once it's been converted to a string. However, it should
never be used to store sensitive or personal data, because it could be called by a malicious script.
There are three calls to know:
localStorage.setItem();
This sets the
localStorage item. It accepts two arguments: the name of the item and the string being stored. You might use it like this:
localStorage.setItem('state', 'true');
And now the next time you visit the page, the browser will know that
'state' is
'true'.
Remember that these are strings;
'true' is not the same as the boolean
true (although as a string, it is truthy).
To call the item, use this method:
localStorage.getItem('state');
It only accepts one argument: the name of the
localStorage item. This will return the string
'true', which we set in the previous method and can be evaluated:
if (localStorage.getItem('state') === 'true') { // This evaluates to the boolean true
console.log('The state is true!');
}
If the item has not been set, it will return
null, which you can use to check for the item and set it if it doesn't exist. Something like this:
if (localStorage.getItem('state') === null) {
localStorage.setItem('state', 'true');
}
To remove the item, use this method:
localStorage.removeItem('state');
This will remove the item completely, if you want to erase it.
There's also this:
localStorage.clear();
Which removes
all localStorage items. I don't recommend using it in your script, for that reason. I only use it to test.
---
You can reference this CodePen for a simple example of how
localStorage might be used to set styles:
codepen.io/ellimccale/pen/MZNXKY---
Hopefully this helps you. Here are the docs from MDN with a little more detail on each method:
developer.mozilla.org/en-US/docs/Web/API/Window/localStoragedeveloper.mozilla.org/en-US/docs/Web/API/Storage/setItemdeveloper.mozilla.org/en-US/docs/Web/API/Storage/getItemdeveloper.mozilla.org/en-US/docs/Web/API/Storage/removeItem