Friday, 22 August 2014

Making our web storage program useful


In the series thus far, we've been building a web storage app that is pretty useless (if you don't know why, you should check out the latest post in this series)

In this post, we'll make that app finally useful and unleash the power of web storage API on the world!

Alright, our application is good to go, but why didn't we just use variables instead of web storage for this application, well, honestly, we could have used plain old variables, but that's not what the W3C made web storage for. The web storage API was made to store information and still have it if the person navigates away from your website and then returns...

So, let's modify our program so that it displays a list of all the items ever stored instead of just showing what you've just typed (assuming you made the changes mentioned in the previous post)

Building the disp( ) function

The first thing we're going to do is reference the right box because all of our stuff happens there. Then, we're going to clear up the text that is there in the right box by setting its inner HTML to "".
var box = document.getElementById("right");
box.innerHTML = "";
Then we're going to loop over all the elements in our session storage and then display them in the right box. I'm first going to show you the code and then explain it to you.
for(var i=0; i < sessionStorage.length; i++){
    var key = sessionStorage.key(i);
    var val = sessionStorage.get(key);

    box.innerHTML += key+": "+val+"<br />";
}

  • The Loop: The loop is fairly straightforward. We initialize a variable called i to 0, we loop as long as i is less than the length of sessionStorage.
  • Line 1: We fetch the key at position 'i' using the key method.
  • Line 2: We then fetch the value that corresponds to the key using the get method that we've been using all this while.
  • Last Line: We finally append that information to the box in the form "key: value" followed by a newline.

Putting it all together and conclusion

Here's what your function will look if you hook up everything you learned in this tutorial correctly: 
function disp(){
    var box = document.getElementById("right");
    box.innerHTML = "";

    for(var i=0; i < sessionStorage.length; i++){
        var key = sessionStorage.key(i);
        var val = sessionStorage.getItem(key);

        box.innerHTML += key+": "+val+"<br />";
    }
}
Now, we're pretty much done, we have a working web storage app, not to mention useful. In the next post, I'll mention some final thoughts on this app. Also, if you notice, all the data expires if the browser is closed. I will also teach you to make it remain forever and also how you should manage so much of power.

No comments:

Post a Comment