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.
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
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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
1 2 3 4 5 6 7 8 9 10 11 |
//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:
1 2 3 4 5 6 7 8 9 |
//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;
1 2 3 4 5 6 7 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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!
Gilles Ruppert
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.
Elisha Chirchir
Thank you for the tip Gilles. Thank you for the comment as well.
Devin
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(); “
Elisha Chirchir
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!
Javier Cáceres
Nice site very practical things
Question What program(s) do you suggest or use to write in HTML5 ?
Thank you
Elisha Chirchir
You can write html5 using any editor you like – since you don’t need to download anything really. You can just add the script cdn of the api you want and that is it.
Good luck.
Thanos
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
Elisha Chirchir
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!
Judah
hey Elisha – nice work all around. am looking for more tutorials like these that cover fundamental concepts. any recommendations? will be sure to complete what you have written here. well done.
Elisha Chirchir
It has been really long since I did these tutorial; but if I run into other nice ones, I will share!!