Local Storage 101

Local Storage 101

November 25, 2015

It's been said that Local Storage is nothing but a shelf.* Shelves may not be the most head-turning things in the world, but when you need to store something that can be readily available, a shelf can be incredibly useful. Javascript variables stored in memory are completely lost when you do a page refresh. Web Storage allows you to put Javascript variables on a shelf, go away and do other things like refresh the page, and then when you come back, you can access that Javascript variable.

Web Storage is broken down in to two pieces: sessionStorage and localStorage. Both allow you to save information that can be accessed after a page refesh, except localStorage is a little more hard-core about for how long it is stored, other than that the API is the same. I’ll talk about localStorage first, and then get in to the differences between localStorage and sessionStorage later in this article.

Local Storage

var myShelf = localStorage;

We’re saving the localStorage object as a variable called myShelf. This isn’t doing much but its a good way to start. What we need to do now is add a key-value pair to it.

setItem()

var myShelf = localStorage;
myShelf.setItem("pictureFrame", "Family Vacation Photo");

setItem() allows you to add a new key-value pair to localStorage. So in this case pictureFrame is the key, and the value is Family Vacation Photo.

By using console.log() below, we can see what we have in localStorage.

var myShelf = localStorage;
myShelf.setItem("pictureFrame", "Family Vacation Photo");
console.log(myShelf);
//Storage {pictureFrame: "Family Vacation Photo"}

Keeping it real

Let’s apply this to a real use-case. Let’s say we want to show an alert with some messaging. The alert will also have a checkbox to not show it again. If the user selects the check box to not show again and dismisses the alert, it shouldn’t show again the next time the user goes to the site. If the user doesn’t check the checkbox and dismisses the alert, then it will appear again next time they visit the site. Here’s the HTML:

<!--HTML-->
<div class="alert">
  <a href="#" class="close-alert">Close</a>
  <h2>Alert title</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
  <input type="checkbox" id="dont-show-again" name="dont-show-again" />
  <label for="dont-show-again">Dont show again</label>
</div>

The key things about this alert is that it has a checkbox with an id of “dont-show-again” and an anchor with a class of “close-alert”. If the checkbox is checked when we close the alert, then we don’t want to show the alert again when the user returns to the site, or just simply refreshes the page. So what we need to do is create a new localStorage variable that we’ll call showStatusStorage that should have a property of “showStatus” with the default value of “show”. We can then write some javascript that checks if the checkbox is selected and then changes the value to “dontShow”. Notice I’m not using the boolean (true or false). The downside of localStorage is it only accepts strings. There are some work arounds to this that we’ll get to later in this article.

var showStatusStorage = localStorage;
showStatusStorage.setItem("showStatus", "show");

We saved localStorage as a variable called ‘showStatusStorage’. Great name. And then called the setItem() method on it to create a new key-value pair of “showStatus” and “show” respectively. Conundrum. The problem with this is that every time we refresh the page, this key-value pair will be set to “showStatus” and “show”. This will do us no good because that will override any values we set and want to save across browser sessions. So what we really need to do is check to see if this key exists already, and only set its corresponding, default value, if the key doesn’t exist. We can use the getItem() method for this.

getItem()

So we feed the getItem() method a key name, in our case “showStatus”.

var showStatusStorage = localStorage;
//test to see if local storage is already set on page load
if (!showStatusStorage.getItem("showStatus")) {
  showStatusStorage.setItem("showStatus", "show");
}

This allows us to check to see whether the “showStatus” key name already exists. The getItem() method returns the value of the key name you pass to it, unless it doesn’t exist yet, and in that case it returns null. Since null does not equal true if our key name doesn’t exist the control flow of our code will go inside the if statement (i.e. if (!showStatusStorage.getItem("showStatus")) { }). Once inside the if statement, we’ll use the setItem() method to add the “showStatus” key name with a value of “show”. So this is saying let’s create the key name of “showStatus” with a default value of “show”, if and only if, it hasn’t already been set. So now once its been set, if we refresh the page, it doesn’t get overwritten. Got all that?

Closing the alert and updating the value in localStorage

Now let’s change the value that lives in localStorage when someone closes the alert.

function closeAlert() {
  $(this).closest(".alert").addClass("hide");
  if ($("#dont-show-again").is(":checked")) {
    showStatusStorage.setItem("showStatus", "dontShow");
  }
}
$(".close-alert").on("click", closeAlert);

The function, closeAlert(), first is simply finding the container element for the alert and adding the “hide” class to it. This makes it go away assuming the css for “hide” is .hide { display: none; } or some other CSS to visually hide the alert.

The if statement is checking to see if our “don’t show again” checkbox is checked, and if so, we are simply updating the value of “showStatus” to “dontShow”. setItem() will create a new key-value pair if the key doesn’t exist. And if the key does exist, like it does in our case, it will just update the value.

Hiding the alert

Now how do we tell the alert to not show up next time the user travels to our page if they had previously checked the “do not show again” checkbox? One way to do this is to start with the alert hidden by adding the “hide” class to the alert. Again, provided that the CSS for this class looks like this: .hide { display: none; } or some other CSS to visually hide the alert.

<!--HTML-->
<div class="alert hide">
  <a href="#" class="close-alert">Close</a>
  <h2>Alert title</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
  <input type="checkbox" id="dont-show-again" name="dont-show-again" />
  <label for="dont-show-again">Dont show again</label>
</div>

We should now remove the “hide” class if the the value of showStatus equals show.

if (showStatusStorage.getItem("showStatus") === "show") {
   $(".alert").removeClass("hide");
}

And that wraps up our real-life example. Fist pump. Booyah. Here’s what all the code should look like.

//store local storage in a variable
var showStatusStorage = localStorage;
//test to see if local storage is already set on page load
if (!showStatusStorage.getItem("showStatus")) {
  showStatusStorage.setItem("showStatus", "show");
}
//show the alert IF the user hasn't expressly checked the 'dont show again' checkbox on a previous visit
if (showStatusStorage.getItem("showStatus") === "show") {
   $(".alert").removeClass("hide");
}
function closeAlert() {
  $(this).closest(".alert").addClass("hide");
  if ($("#dont-show-again").is(":checked")) {
    showStatusStorage.setItem("showStatus", "dontShow");
  }
}
$(".close-alert").on("click", closeAlert);

Non-string values, and the lack thereof.

So one of the weird things about localStorage is that all of the values are stored as strings. Even if you provide a non-string value, like 5 or false, they will be stringified as “5” and “false”. Instead of using values like, “dontShow” and “show” it would be much easier to use boolean true/false values. One thing you can do is wrap your localStorage in JSON.parse().

showStatusStorage.setItem("showStatus", true);
console.log(showStatusStorage.getItem("showStatus"));
//"true"
console.log(JSON.parse(showStatusStorage.getItem("showStatus")));
//true

Web Storage

localStorage falls under the W3C’s Web Storage specification that defines an API for persistent data storage. There are two primary parts: localStorage and sessionStorage.

What this boils down to is sessionStorage is like localStorage Light. The API for sessionStorage is identical to localStorage. But think of sessionStorage as connected directly to the browser tab you have open. Once that browser tab is closed the sessionStorage is cleared. So this lets you do a page refesh and keep your sessionStorage, but as soon as you close your browser tab, your sessionStorage is erased. Also, if you have two browser tabs open to the same website, the sessionStorage will not spill over in to the other tab. Each tab will have its own unique sessionStorage. localStorage on the other hand is more hard-core. Close your browser tab, close your entire browser, shut down your computer, cryogenically freeze yourself for a year, and when you return in the future and boot up your computer, your localStorage will still be there.

Removing items from localStorage

So then how do we remove, localStorage and sessionStorage. There are two methods provided to do this: Clear everything, or one item at a time.

clear()

This method accepts no parameters and clears everything in storage.

showStatusStorage.clear();

removeItem()

This method accepts a string as a parameter that is the key name of the one item you want to clear. You cannot clear two items at one time.

showStatusStorage.removeItem("showStatus");

Clearing storage via browser options

sessionStorage is cleared by the user if they close their browser tab. localStorage is a little bit more stubborn to clear by the user. In Chrome, if I do an “Empty Cache and Hard Refresh” the localStorage isn’t cleared.

Using the keyboard shortcut shift + command + delete on Mac or shift + control + delete on Windows, I’ll need to check the box for Cookies and other site and plugin data. This will clear the localStorage in Chrome.

In Firefox, the keyboard shortcut is also shift + command + delete on Mac or shift + control + delete on Windows. The difference is I’ll need to check the Cookies checkbox to remove the localStorage. Although, different than a cookie, its close enough where browsers are lumping localStorage and sessionStorage in the same category as cookies.

Browser Support

Super good. IE8 supports localStorage.

Live example

See the Pen Local Storage Example by Rich Finelli (@richfinelli) on CodePen.

That’s about it

localStorage is fairly awesome for storing data that isn’t mission critical to your application. Its better than a cookie in a number of ways including the size limit is around 5MB instead of 4KB and the API is much simpler. On the otherhand, localStorage isn’t nearly as good as actually saving user-data to a database because the localStorage can get cleared by the user and isn’t persistent across browsers. So if I access the web page from Firefox and then later on Chrome, the localStorage‘s will not be in-sync. However, localStorage is still pretty darn sweet.

*In Jake Archibald’s A List Apart article, Application Cache is a Douchebag the Application Cache calls Local Storage nothing more than a shelf while talking to a girl at a party.

Mastering CSS: Book by Rich Finelli
Mastering CSS, the Book! Flexbox, Layout, Animations, Responsive, Retina, and more!
Mastering CSS, 2nd Edition, video course by Rich Finelli
Mastering CSS, Second Edition: 47 videos on how to make websites like a boss! Flexbox, Animations, Responsive, Retina, and more!
Back to top