As part of the range of new HTML5 Javascript goodies localStorage allows developers to store data client side for later reuse. Sounds familiar? Yep, just like cookies, but without the size limitations as you can store Megabytes of data using localStorage.

Setting Values

To set a localStorage value you use the method setItem().

localStorage.setItem(name,value);

So to set a value of ‘Creamy Lancashire’ to an item named ‘cheese’ we would use:

localStorage.setItem('cheese','Creamy Lancashire');

Getting Values Back

To get values back from localStorage we use the getItem() with the syntax:

localStorage.getItem(name);

So the cheesy example would be:

var perfectWithBiscuits = localStorage.setItem('cheese');

Optional extra info on getters and setters (Tell me more)

Getters and Setters

An alternative to the methods of setItem() and getItem() is to use the ‘name’ as a getter/setter. An alternative way to get and set values would therefore be:

// to set
localStorage.cheese = 'Creamy Lancashire');
// to get
var perfectWithBiscuits = localStorage.cheese;

Both should be supported but as ever check with your target browsers. One difference is the messages returned when the values are not set. The setItem() method returns null whilst the getter returns undefined.

View Demo

An Example with a Colour Picker

In this demo localStorage is used to store the background colour you pick, such that when you return to the page after closing the browser it remembers your choice.

//set value
localStorage.myBgColour=newColour;
//get value
bgColour = localStorage.myBgColour

The rather neat Javascript Colour picker here comes courtesy of Spectrum.

View Demo

Leave a Comment