Friday, 8 August 2014

HTML5 Web Storage API (Part 3)


Alright people! In this tutorial we're finally going to start coding and I'll be teaching you guys: how to use the Web Storage API of HTML5.

By the way, in order to keep up with my policy of not stuffing in too much of technical content in one post and frustrate you guys, in this post, I'll only talk about storing data in our client's browser. In the next tutorial we'll talk about retrieving information...

Setting up an initialization function

Now, when the application finishes loading, we need to call a function that does all the "housekeeping work" like referencing all the elements, attaching event listeners etc. So, we'll build a function called init() that gets called when the browser has loaded.
window.addEventListener("load", init);

Building the initialization function

Our initialization function just has two things to do:
  • Reference the button element
  • Add an event handler to respond to the button's clicks
So, that's really easy functionality to implement:
function init(){
    var button = document.getElementById("submit");
    button.addEventListener("click", save); 
    // So we'll call the save function when the button is clicked...
}

Now comes the meat of this tutorial...

What do we want to do when the button is clicked, i.e. when the save function is called? Well,
  • First, we want to grab the values in the two text boxes.
  • Then, we want to store the values as a key-value pair in the browser.
Getting the values of the two text boxes is easy:
var key = document.getElementById("box1").value;
var value = document.getElementById("box2").value;
Now, how do we save the information that we just obtained.

Well, for that purpose, we have an object in JavaScript called sessionStorage which has a method called setItem. This method takes in two parameters, a key, and a value. Thus to store the information in the client, we can use the setItem as follows:
sessionStorage.setItem(key, value);
So, our save function should finally look like:
function save(){
    var key = document.getElementById("box1").value;
    var value = document.getElementById("box2").value;

    sessionStorage.setItem(key, value);
}

Conclusion

So, now that you've learned to save information in the client, you're good to go and you can proceed to the next tutorial.

I just hope I didn't stuff too much of technical information in this post and in the next post, we'll learn to retrieve the information back from the browser.

No comments:

Post a Comment