How to store JavaScript values persistently, locally

So, you want to store data on the client side?  There is a method called localStorage.  Let’s do a simple example.

 

 

This very simple example simply writes the “coffee” values from the local variable, to localStorage, and back to another local variable but it shows the potential of localstorage. Let us take a look at a slightly more complicated example.

 

 

This example gets you a little closer to an actually useful implementation of the concepts.  It takes the values you enter into the text box and adds it to localstorage.  It also populates the unordered list with the contents of localstorage.  So, how can we take it a step further?

 

 

Functionally, this example is identical to the one above.  It does, though move the functions into a namespace.  How does this help?  Well, let’s say that we want to keep a list of both Sally’s favorite coffees and a list of Bob’s favorite coffees?  AddCoffee() is a little generic.  There is a good chance of a collision in function names.  This helps to prevent that.

Now that you understand localStorage, you might want to check out sessionStorage.  It’s just like localStorage except it only lasts as long as the browser window (or tab) is open.  Where localStorage might be better for storing user preferences, sessionStorage might be better for storing a shopping cart.  Please keep in mind that neither localStorage nor sessionStorage work with IE7 and older.  If you need to support IE7, you might need to look towards using cookies for your application.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>