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


Hello!This is the third post on how to use html5 web storage api to create a simple web application (sticky notes). If you have not read the second post, please click here to get started before going forward – although it is up to you to choose. Today, I am going to complete the app by adding some improvements and fixing some potential errors in the design. Enjoy with me!

html5 web storage 300x183 How To Build  Simple App Using HTML5 Web Storage API   Part III

Before the end of my second post in this series, we had something that looked like this:

sample sticky notes 300x180 How To Build  Simple App Using HTML5 Web Storage API   Part III

That was all nice and pretty but what if you wanted to delete the sticky notes? Assuming you didn’t know about the developer tools that come with most modern browsers, it would be an issue. Today, I want to show you how you can do that and then move on to other good stuff.


<!doctype html>
<html>
   <head>
       <title>HTML5  - Cleaning up storage</title>
       <meta charset="utf-8">
       <script>
            window.onload = function() {
                 var clearButton = document.getElementById("clear_button");
                 clearButton.onclick = clearStorage;
            }
            function clearStorage() {
                 localStorage.clear();
            }
       </script>
   </head>
   <body>
       <form>
             <input type="button" id="clear_button" value="Clear storage" />
             </form>
   </body>
</html>

Now you can simply click a button and all your sticky notes will be deleted. One more thing to note here is that this clear() method wipes everything out of the localStorage and not just sticky notes.

Possible Design Flaws In Our App

In my previous post, I said that we were going to design our app such that keys stick to the following naming convention: sticky_0, sticky_1, sticky_2, sticky_n. There is a problem as a result of this: consider a situation where you have stored other stuff, non-sticky notes in the localStorage. Think about it.

What will happen when you are iterating through localStorage to print out the sticky notes? Now think of having a lot of non-stickies stored in there too. Will that be efficient? It can also be difficult to tell the number of sticky notes in localStorage because you have to look through all the items stored.

A better solution to this problem – Using Arrays

I stated earlier that you can only store strings. Now am talking about arrays and you are probably thinking…how will that work? JSON.stringify() and JSON.parse() will come to the rescue here.

A rewrite of our functions

//the whole code

window.onload = init;

function init(){
    var button = document.getElementById("add_sticky");
    button.onclick = makeSticky; //defined below

    var stickiesArray = getStickiesArray(); //I will define and explain

    for (var i=0; i < stickiesArray.length; i++){
        //no longer iterating through localStorage ---good idea
        var key = stickiesArray[i];
        var value = stickiesArray[key];
        addStickyToPage(value);
     }
}

//define getStickiesArray function

function getStickiesArray(){
     var stickiesArray = localStorage.getItem["stickiesArray"];

     //check if it exists
     if (!stickiesArray){
        //create one below if not
        stickiesArray = []

        //now store the array
        localStorage.setItem("stickiesArray", JSON.stringify(stickiesArray));
     }
     else{
        stickiesArray = JSON.parse(stickiesArray);
     }
     return stickiesArray;
}

//define makeSticky function
function makeSticky(){
     var stickiesArray = getStickiesArray();
     var currentDate = new Date();
     var key = "sticky_" + currentDate.getTime();
     var value = document.getElementById("note_content").value;

     localStorage.setItem(key, value);
     stickiesArray.push(key);
     localStorage.setItem("stickiesArray", JSON.stringify(stickiesArray));

     addStickyToPage(value);
}

//define addStickyToPage function
function addStickyToPage(value){
    var stickies = document.getElementById("stickies");
    var sticky = document.createElement("li");
    var span = document.createElement("span");
    span.setAttribute("class", "sticky");
    span.innerHTML = value;
    sticky.appendChild(span);
    stickies.appendChild(sticky);
}

Explanation of the code

A few things have happened above. If you have been following from the first post, you might have noticed a slight change in the init function. Let us step through the updates:

  • Instead of using the localStorage’s length to know how many stickies we have, we have defined a variable whose value is the return value of calling getStickiesArray function.
  • We are now iterating through the array instead of the entire localStorage. During the looping process, we call addStickyToPage function like we did in the beginning(post 2).
  • Then we defined getStickiesArray function that does the heavy work of getting the array from the localStorage and checking to see if it exists or not. It also creates one if it doesn’t. Before storing the newly created array or returning it, it uses JSON.stringify() or JSON.parse() respectively to make sure everything is in the right format.
  • Inside makeSticky function, I have introduced something new. Instead of using the length of localStorage to make our sticky notes keys unique, we append the current time to the word “sticky_”.

As you can see, we have made some significant improvements to our web application. If you run this code right now, you might not notice much of a difference in the look on your browser but from the code, you can clearly tell the improvements.

There are several things that we could add to this web app to make it sexier – if there is anything as such.

  • Enable a user to simply click on a given sticky note to delete it.
  • Add different colors depending on what the user chooses
  • Wipe the slate clean with a single button click and start over
  • Even more stuff – share them with me if you have some

Thank you for stopping by. If you read this entire post, you have found some cool things you can do with html5 web storage. Though simple, it sure can be fun to play around before moving up a level.

If you liked this post, please consider sharing it using the buttons below with your online friends. I will truly appreciate that. If you have any questions, please let me know. If you think I should add the above listed features, don’t hesitate to drop me a line in the comments so I can do so. If you do it yourself, let me see how you did it.

Thanks again and see you soon!

 


2 thoughts on “How To Build Simple App Using HTML5 Web Storage API – Part III

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="">