How To Build a Simple App Using HTML5 Web Storage API – Part I

Hello there! It is nice to see you here (I am not really seeing you). Today, I am getting back to serious business – sharing what I have learned over the years and writing some markup and code as we go. This post will be in two parts. This is the first part. HTML5 is something we cannot ignore anymore, at least that is what I think. So what is Web Storage API? We will find out soon.

how to build app using html5 300x254 How To Build a Simple App Using HTML5 Web Storage API   Part I

Most developers are used to storing client data in a cookie. Cookies are limited to 4K of data. Today however, it doesn’t take much effort to realize that we need more space. That is where HTML5 Web Storage comes in.

Here Comes HTML5 Web Storage

HTML5 gives us a nice and simple JavaScript API in the browser for storing key/value pairs that are persistent. You are not limited to just four kilobytes of storage in every user’s browser. You can use it with both web and mobile apps. This can help your app reduce communication with the server. Most modern browsers come with at least 5MB of storage space and we are going to use it now!

Taking Your Sticky Notes To The Web

how to create sticky notes How To Build a Simple App Using HTML5 Web Storage API   Part I

Instead of creating all the trash and killing the only left trees out there, we should create our stickies using HTML5 and save the planet. We will see how to do that starting now. It is really easy to store something in the browser using Web Storage API.

The index.html file


<!DOCTYPE html>

<html>

    <head>

       <meta charset="utf-8">

       <title>HTML5 - Using Web Storage </title>

       <script src="main.js"></script>

   </head>

   <body>

       <!-- will use this later --->

   </body>

</html>

The main.js file


window.load = init;

function init(){

    localStorage.setItem("note_1", "Going bike riding with friends");

    localStorage.setItem("note_2", "Swim because it is summer");

    var note = localStorage.getItem("note_1");

    alert(note);

}

Indentation: For some reason, this syntax highlighter doesn’t retain the code formatting as I would like it. 

You might have suspected what is going on here already but I will explain it briefly: First we created a simple html page called index and then created a javaScript file called main. I linked to it in the header section as usual. In the main.js file, I did a few things:

  • To make sure the script runs  after the window has finished loading, I used a window.onload function. Now, I used a separate function called init to do the good stuff.
  • Inside init, I simply added notes to the localStorage – which has a method called setItem that takes two strings, key/value pairs. It is that simple.
  • After storing stuff, you can easily retrieve them using getItem method of localStorage. You pass in a key and you get the value back. Really fun!

If you run that script – load the page on your browser, you will get an alert window displaying the first sticky note. You can display the second one if you are following along.

That is not very exciting right?

Up until now, we can store data and get them back. Getting them back doesn’t mean removing them. Earlier on, I stated that you can only use strings as keys and values and  you are probably thinking, what about numbers and other types? Don’t worry; there is a solution to this problem: store an integer as a string then convert it back to its original type when you want to use it!  We will make our app more useful and more exciting as well. Let us improve it.

Example


  //inside our init function from previous script

  localStorage.setItem("total_hours", 24);

  alert(localStorage.getItem("total_hours"); //what will happen here?

  //try thinking through it before reading further.

What happens is that localStorage expects a string and so it converts the 24 into a string before storing it. While retrieving it, we have to convert it ourselves because javaScript is not that smart. Here is how we do it:


   //use parseInt() to convert back to int

   var total_hours = parseInt(localStorage.getItem("total_hours"));

   //use parseFloat() for floats.

localStorage as an associative array

One awesome thing about the localStorage API is that you can actually use it as an associative array meaning you can add key/value pairs and retrieve them without using setItem and getItem methods. Take a quick look;


   localStorage['name'] =  'Simple Developer Blog'; //stores it

   var name = localStorage['name']  // retrieves Simple Developer Blog

More cool stuff that localStorage has

You can easily find the length of the localStorage using the length property and you also get a method called key()  which gets all the keys stored from which you can get values associated with them.

Example:


for (var i=0; i < localStorage.length; i++){

   var key = localStorage.key(i);

   var value = localStorage[key];

   console.log(value);

}

Basically, what we are saying is this: for every item in the localStorage, give us the key for example note_1 or name etc.

Coming up next in this series ……the real sticky app

Since I am considerate enough, I will stop here because I believe this post is getting longer than it should. I have given a brief introduction to this exciting HTML5 Web Storage API. You now know several things about it:

  • To add data you use either setItem or as you do in associative arrays.
  • localStorage allows strings as keys and values but you can store integers and floats by converting them from one type to another (String ->int, String ->float and vice versa).
  • localStorage has length property.
  • localStorage has a method called key that returns all the keys from localStorage.

In the next post, we will create a simple web application that will allow you to add more sticky notes to the storage, delete them and use css to style ‘em up like pros do. I hope you are excited about this and are ready to learn more.

Thank you for reading through this post. If you have any questions, please let me know and I will be more than happy to answer them.

If you have comments or ideas, let me know. If you liked this post, please consider sharing it with your friends online. Are you on Twitter? Please follow me – I follow back! Thank you and see you tomorrow!

 

 

 

8 thoughts on “How To Build a Simple App Using HTML5 Web Storage API – Part I

  1. Just little tip: move the main.js script tag just above the closing body tag. That way you can get rid of the window load event, which is faster.

  2. Thanks for this, getting to understand localstorage better.

    Although in the JS file ” window.load = init; ” didn’t work for me, I had to use ” window.onload = init(); “

    • First, thanks for stopping by and reading through this guide. I appreciate the comment. I am sorry about the js file not working as it should. I am glad you were able to fix it. If you have any further questions, don’t hesitate to let me know. See you soon and update me on your progress!

  3. Hey man what a nice site congrats.
    I would like to ask what text editor are you using i like it very much. i am learning coding on my own and i dont have any mentors to give tips about what editor to use

    • I personally use Sublime Text 3 – which is free to try with a non-expiring license for now. I also use Intellij – there are two versions (Pro and Community edition).

      Eclipse is also good and totally free of charge!

      You can always contact me if you have questions on programming!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">