Saturday, 9 August 2014

HTML5 Web Storage API (Part 4)


In the previous post we learned about using HTML5's Web Storage API to store information in the browser using sessionStorage.setItem, in this post, we'll learn to retrieve that information back from the user using sessionStorage.getItem...

sessionStorage.getItem

Remember in the setItem method we passed in a key and a value? The getItem method simply takes in that key and returns the value.

Think if it this way: Let's say the setItem function simply creates a variable called 'key' with value 'value'. To retrieve that value you simply call the getItem function and tell it which key's value to retrieve..

The syntax for this is simple:
var value = sessionStorage.getItem(key);

Building the function to display the data in the right box

All this function does is retrieves the data from the sessionStorage using getItem( ) method and sets it as the innerHTML of the right box. It takes in the key for the getItem( ) method as a parameter...
function disp(key){
    var box = document.getElementById("right");
    var val = sessionStorage.getItem(key);
    box.innerHTML = "Key: "+key+"<br/>Val: "+val;
}

Calling the disp( ) function

Though, we've built the function to display the data that we've stored in sessionStorage, we actually need to call it in order to actually display it. So, let's call the function immediately after we store the information in the sessionStorage.

So, we'll modify the save( ) function as follows (the line in bold italics has been added)
function save(){
    var key = document.getElementById("box1").value;
    var value = document.getElementById("box2").value;

    sessionStorage.setItem(key, value);
    disp(key);
}

We're pretty much done, but...

Here's what our application looks as of now:
Our web storage application as of now...
Our web storage application as of now...
View Code View Demo

But no matter how much we try to convince ourselves, the fact remains that this application is useless. I mean, we really didn't have to use web storage API to do what this app does, we could simple change the text of the right box when the button is clicked bypassing the web storage part...

In the next part, I'll try to convince you guys that web storage is indeed usefull (if not this application) by making this application more useful...

No comments:

Post a Comment