A Web Designer & Developer in Wichita Falls, TX. Working for Crane | West Advertising Agency.
James Fleeting
 
11 May

HTML5 localStorage – Part Three

You should now have a good idea of how you can use localStorage yourself. However I promised we would create a simple html5 web app and thats what we are going to do. In this post we are going to get our app setup and ready for use. This means it will allow a user to create new entries in their database, display all the entries and allow them to delete a specific entry or remove all entries. In this post we won’t focus on the design of the app but rather making it functional. Part Four will cover the final steps including the design and adding some fancy css3. So, why am I still talking when you are here to see some code?

First we will take what we learned in the last post and write the function that will allow a user to create a new database entry. In this case, since we are creating a time tracking app, it means adding an item to the time log including project name, hours spent and the date. This means we are going to need a pretty simple form along with some code to run on submit that will store the item in the database. I will be using some jQuery for this code.

Copy to Clipboard
1
2
3
4
5
6
<form id="logForm" method="post">
    <input type="text" name="project" value="Project Name">
    <input type="number" name="hours" value="Hours" class="shortField">
    <input type="text" name="date" value="Date" class="shortField">
    <input type="submit" value="Log Time">
</form>
Copy to Clipboard
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
26
27
28
29
30
if (typeof(localStorage) == 'undefined' ) {
    alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
    $("#logForm").submit(function(){
        var newDate = new Date();
        var itemId = newDate.getTime();
        var values = new Array();
        var project = $("input[name='project']").val();
        var hours = $("input[name='hours']").val();
        var date = $("input[name='date']").val();
 
        //strip html tags
        project = project(/(<([^>]+)>)/ig, "");
        values.push(project);
        values.push(hours);
        values.push(date);
 
        if (project != "" && hours != "" && date != "") {
            try {
                localStorage.setItem(itemId, values.join(';'));
            } catch (e) {
                if (e == QUOTA_EXCEEDED_ERR) {
                    alert('Quota exceeded!');
                }
            }
        } else {
            alert("All fields are required.");
        }
    });
}

Not much new here that we haven’t already gone over. When you submit the above form that chunk of javascript will run which will create a unique id using milliseconds. Then we create a new array that will hold our values. Next we will assign some easy to use variables to our form input values. Before pushing each value into our new array we will strip out any html tags in project name. Our values array now has everything we need. We will first check to make sure the values aren’t empty and if they are lets alert the user. If the values are filled in we will try and store the item in localStorage using our new unique itemId and joining each value in our array with a semicolon. We must do this because localStorage will only store a string. If there were no errors our item is now stored in the database. You can know check the items in localStorage to verify the item was added and to see how it was stored. I detailed this in Part One but in Firefox you need Firebug and under the DOM tab find ‘get localStorage’. In Safari/Chrome open the developer tools and you will find everything under Databases.

Now that we have a way for a user to add new items to the app we still need a way to list all the items in the database. This part is pretty simple, we are going to get all items from storage and for each item display it as a list item. This will build us a nice list to see all the time we have logged in. How you display this information is up to you. In this case we are going to create an unordered list and use .html() to display it. The only html needed is a list with an id for us to target.

Copy to Clipboard
1
2
3
<ul id="theLog">
    <li>Loading&hellip;</li>
</ul>
Copy to Clipboard
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
function getAllItems() {
    var timeLog = ""; //the variable that will hold our html
    var i = 0;
    var logLength = localStorage.length-1; //how many items are in the database starting with zero
 
    //now we are going to loop through each item in the database
    for (i = 0; i <= logLength; i++) {
        //lets setup some variables for the key and values
        var itemKey = localStorage.key(i);
        var values = localStorage.getItem(itemKey);
        values = values.split(";"); //create an array of the values
        var project = values[0];
        var hours = values[1];
        var date = values[2];
 
        //now that we have the item, lets add it as a list item
        timeLog += '<li><strong>'+project+'</strong>: '+hours+' hours - '+date+'</li>';
    }
 
    //if there were no items in the database
    if (timeLog == "")
        timeLog = '<li class="empty">Log Currently Empty</li>';
 
    $("#theLog").html(timeLog); //update the ul with the list items
}

Nothing to crazy going on there but lets go over the javascript anyways. In line 2-4 we are creating an empty variable to hold the html from our list, setting a variable to zero which we will use to loop, then finding how many items are in the database starting with the 0 element. Now for each item in the database we setup some variables including getting the itemKey and the values. Since localStorage only supports a string we will run a .split(“;”) to create an array with our values. Then we set some easy to use variables for each value. Of course this code could be simplified by not creating those variables and just calling values[] but its an attempt to keep it simple and easily show whats going on. Since we have our values we create a new list item and add it to our timeLog. Next we check to see if our timeLog has any values, if it doesn’t lets show that its empty. Finally we replace any html inside our ul#theLog with our new html/list items. Lets go ahead and see what the full html and javascript should look like now.

Copy to Clipboard
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<!DOCTYPE html>
<html lang="en">
<head>
    <title>localStorage()</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script>
    $(document).ready(function() {
        if (typeof(localStorage) == 'undefined' ) {
            alert('Your browser does not support HTML5 localStorage. Try upgrading.');
        } else {
            getAllItems(); //load the items
 
            $("#logForm").submit(function(){
                var newDate = new Date();
                var itemId = newDate.getTime();
                var values = new Array();
                var project = $("input[name='project']").val();
                var hours = $("input[name='hours']").val();
                var date = $("input[name='date']").val();
 
                //strip html tags
                project = project(/(<([^>]+)>)/ig, "");
                values.push(project);
                values.push(hours);
                values.push(date);
 
                if (project != "" && hours != "" && date != "") {
                    try {
                        localStorage.setItem(itemId, values.join(';'));
                    } catch (e) {
                        if (e == QUOTA_EXCEEDED_ERR) {
                            alert('Quota exceeded!');
                        }
                    }
                } else {
                    alert("All fields are required.");
                }
            });
        }
    });
 
    function getAllItems() {
        var timeLog = ""; //the variable that will hold our html
        var i = 0;
        var logLength = localStorage.length-1; //how many items are in the database starting with zero
 
        //now we are going to loop through each item in the database
        for (i = 0; i <= logLength; i++) {
            //lets setup some variables for the key and values
            var itemKey = localStorage.key(i);
            var values = localStorage.getItem(itemKey);
            values = values.split(";"); //create an array of the values
            var project = values[0];
            var hours = values[1];
            var date = values[2];
 
            //now that we have the item, lets add it as a list item
            timeLog += '<li><strong>'+project+'</strong>: '+hours+' hours - '+date+'</li>';
        }
 
        //if there were no items in the database
        if (timeLog == "")
            timeLog = '<li class="empty">Log Currently Empty</li>';
 
        $("#theLog").html(timeLog); //update the ul with the list items
    }
    </script>
</head>
<body>
    <form id="logForm" method="post">
        <input type="text" name="project" value="Project Name">
        <input type="number" name="hours" value="Hours" class="shortField">
        <input type="text" name="date" value="Date" class="shortField">
        <input type="submit" value="Log Time">
    </form>
 
    <ul id="theLog">
        <li>Loading&hellip;</li>
    </ul>
</body>
</html>

Our time tracking web app is finally taking shape. We now allow users to add new items to their database and display those items in a simple list. However, something is still missing. We haven’t given the user a way to delete specific items or clear their time log, which I would say is pretty important to this app. We covered this at the end of Part Two so we know how easy it is. To allow for this we need to edit our html for each list item to include the itemKey along with an icon for delete. To clear the entire log we will add a button below the list and add a .click to it. Lets see what those changes look like.

Copy to Clipboard
1
timeLog += '<li><strong>'+project+'</strong>: '+hours+' hours - '+date+' <span class="delete" name="'+itemKey+'">&times;</span></li>';

The list item now has a delete icon with a class of .delete which we will bind to a .click. You will notice the name on the span is set to our itemKey. This will let us delete that specific item from the database. To make that work we need to add that .click:

Copy to Clipboard
1
2
3
4
5
6
7
8
9
10
$(".delete").click(function() {
    var answer = confirm("Are you sure you want to delete this time?");
 
    if (answer) {
        var itemKey = $(this).attr("name");
        localStorage.removeItem(itemKey);
 
        getAllItems(); //refresh the list of items
    }
});

Now we need to add a Clear Log button just below our list that will give users an easy way to clear the log. We will need to add the button to our html and add another .click that will clear the log.

Copy to Clipboard
<button type="button" id="clearLog">Clear Log</button>
Copy to Clipboard
1
2
3
4
5
6
7
8
9
$("#clearLog").click(function() {
    var answer = confirm("Are you sure you want to clear the log?");
 
    if (answer) {
        localStorage.clear();
 
        getAllItems(); //refresh the list of items
    }
});

We can finally see this web app taking shape. You should now be an expert at using localStorage. Although it may not look like much the functionality is there. In Part Four, the final post in this series, we will style the entire app to look like an iPhone(ish) web app. We will also get rid of those alerts() and add some dialog’s and a date picker to the form using jQuery UI. You can see a working demo of the above code here to see it working in a browser.

 

Add Your Comment