API
The full API specification for the
localStorage and sessionStorage objects can be found here. At the time
of writing, this is how the common Storage interface look:
Demo
I’ve put together a quick demo here to illustrate how to detect and use the local and
session storage to get, set, remove and clear stored items (well, basically,
covers each of the available methods on the Storage interface
above).
The page itself is simple and crude, just a couple of <div>
and most importantly two tables which I use to show all the key value pairs
stored in the local and session storage:
Introducing the new placeholder attribute
You might have noticed that the two text boxes had placeholder text
similar to that familiar search box in Firefox:
This is done using HTML5’s placeholder attribute for the <input> tag:
1
2 |
< input id = "keyText" placeholder = "Enter
key" />
< input id = "valueText" placeholder = "Enter
value" />
|
Nice and easy, eh?
Setting an item
To add a new key value pair or update the value associated with an
existing key, you just have to call the setItem method on the intended
storage object:
1
2
3
4
5
6
7
8
9
10
11
12
13 |
function setKey()
{
var key
= $( "#keyText" ).val();
var value = $( "#valueText" ).val();
if (Modernizr.localstorage) {
localStorage.setItem(key,
value);
}
if (Modernizr.sessionstorage) {
sessionStorage.setItem(key,
value);
}
showKeys();
}
|
Removing an item
Earlier in the showStorageKeys(type, table) function, I added a
row to the relevant table for each key value pair in the storage including a
button with a handler for the onclick event. The handlers are
created with the correct storage type (“local” or “session”) and key for the
current row baked in already so that they will call the removeItem(type,
key) function with the correct parameters:
1
2
3
4
5
6
7 |
function removeItem(type, key) {
var storage = window[type + 'Storage' ];
storage.removeItem(key);
showKeys();
}
|
Clearing all items
Finally, the ’”Clear” buttons underneath the tables call the
clearLocalKeys() and clearSessionKeys() function to remove all the key
value pairs in the corresponding storage:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 |
function clearLocalKeys() {
clearKeys( "local" );
}
function clearSessionKeys() {
clearKeys( "session" );
}
function clearKeys(type) {
var storage = window[type + 'Storage' ];
storage.clear();
showKeys();
}
|