Building HTML5 Mobile Apps with Local Storage and Topcoat

In this tutorial, we will take a look at a fundamental use case of the local storage object by explaining how the API works and creating a simple application using jQuery and Topcoat. You can learn more about mobile HTML5 in my online course.

The API

Sometimes it makes sense to save some persistent data on the end user’s device, we can do this and more with out using a server-side programming language—meet local storage!

Local Storage is part of the HTML5 APIs - it is an object and we can access this object and its functionality via JavaScript. During this tutorial, we will use JavaScript to take a look at the fundamentals of the local storage object and how we can store and retrieve data, client side.

Requirements

  1. Text Editor
  2. Web Browser
  3. HTML Basics
  4. JavaScript Basics

You can download the source code here.

Local storage items are set in key/value pairs, so for every item that we wish to store on the client (the end user’s device), we need a key—this key should be directly related to the data that it is stored alongside.

There are multiple methods and an important property that we have access to, so let’s get started.

You would type this code into a HTML5 document, inside your script tags.

Setting Items

First up, we have the setItem() method, which takes our key/ value (or sometimes referred to as name/ value) pair as an argument. This method is very important, as it will allow us to actually store the data on the client; this method has no specific return value. The setItem() method looks just like this:

localStorage.setItem("Name", "Bob");
localStorage.setItem("Job", "Developer");
localStorage.setItem("Address", "123 html5 street");
localStorage.setItem("Phone", "0123456789");

As you can see, we have stores some data-- keys and values. Our keys are Name, Job, Address and Phone and the values are the data following the comma, so we have Bob as the Name, Developer as the Job, 123 html5 street as the Address and 0123456789 as the Phone number.

Getting Items

Now that we have had a look at storing some data, let’s get some of that defined data out of local storage. To do this, we have the getItem() method, which takes a key as an argument and returns the string value that is associated with it:

localStorage.getItem(“Name”);

The return value of this invocation will be Bob.

Now, let’s take a look at returning all of our items and logging them out to the console in your browser.

console.log(localStorage.getItem("Name"));
console.log(localStorage.getItem ("Job"));
console.log(localStorage.getItem ("Address"));
console.log(localStorage.getItem ("Phone"));

Your console should now display something like this (depending on what data you set in the local storage):

Local Storage Output

Removing items

Another method of interest to us is the removeItem() method. This method will remove Items from local storage (we will talk a little more about ‘emptying’ local storage later). The removeItem() method takes a key as an argument and will remove the value associated with that key. It looks just like this:

localStorage.removeItem("Name");

So now, when we log out our previously set items with the getItem() method, we will only have 3 values logged in the console of the browser (and one null):

Local Storage Output

Retrieving keys

There is also the key() method—the key method takes an index as an argument and returns the key of the associated index:

console.log(localStorage.key(0));

Local Storage Output

As you can see, we have logged out the key associated with index zero. But, as you may have noticed, it isn’t logging out the first item that we set (which was “Name”), this is because local storage saves data in alphabetical order, so when we use the key() method, we must keep in mind that the keys are stored in alphabetical order.

Why persistent data

Local storage data is persistent, meaning that the data remains in the end user’s device until they either manually clear out their local storage or we use a method, called clear().

Now, before we take a look at the clear method, it is important to note that the clear (and the removeItem()) method will only remove local storage data from the client when the removeItem() or clear() method is called from a web service that is on the same domain, same port number and the same protocol as the service that set the items (“same origin”). This can be a little tricky to understand, so let’s say that we are coding some local storage JS on http://example.com, we cannot remove any local storage data that was set by http://example.com from https://example.com nor http://example.com:2086.

Also, remember that this holds true for all local storage data and methods—meaning that we can only access or delete local storage items when the above criterion have been met.

When taking a look at this clear() method in action, I will also be using one of local storage’s properties attributes—length. The length attribute will tell us how many items are currently in local storage, with the above criterion in mind.

console.log(localStorage.length);
localStorage.clear();
console.log(localStorage.length);

Local Storage Output

As you can see, we started off with four items, and then ended up with zero items, after invoking clear().

The use case

The use case that we will be taking a look at will be addressing the issue of connectivity in mobile devices. We are going to build a simple HTML5 contacts app that will read data regardless of whether there is currently an internet connection or not.

Additional Requirements:

  1. Local Server
  2. jQuery
  3. Topcoat
  4. Normalize

We will be using jQuery’s getJSON() method to read in some contacts from a simple JSON data model and save the data into local storage. This is a very powerful concept as when developing HTML5 Mobile Applications, the user will have an internet connection some times and other times, not. So, when the user is able to successfully read in the data, we will store the data in local storage and in the case that the user is unsuccessful in reading in the data, we will check local storage and if the data exists in local storage, we will read in the data from local storage.

The directory structure

This is what our directory structure should look like: Local Storage Directory Structure

The data model and Markup

This is what our JSON data model should look like:

{

    "contacts": [

        {   "first"   : "Joe",          "last"    : "Bloggs"        },
        {   "first"   : "Mary",             "last"    : "Johnson"       },
        {   "first"   : "Paul",             "last"    : "Smith"                 },
        {   "first"   : "Tina",     "last"    : "Clarks"                }

    ]

}

And our HTML5 Markup:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Local Storage</title>
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/topcoat-mobile-dark.min.css">
        <style>#contacts ul{text-align: center;}</style>
    </head>
    <body>
        <section class="topcoat-list__container" id="contacts"><ul class="topcoat-list"></ul></section>
        <script src="js/jquery.min.js"></script>
    </body>
</html>

As you can see, I have included the TopCoat dark minified CSS and the normalize CSS reset

Let’s get started with some JavaScript (I will be placing the JavaScript just under the inclusion of the jQuery library in the HTML file).

<script>
$(document).ready(function(){

    $.getJSON("data/data.json").done(function(data){

        localStorage.setItem("data", JSON.stringify(data));

        $.each(data.contacts, function(index, value){

            $("#contacts ul").append(
                "<li class='topcoat-list__item'>\
                    First Name: " + value.first + "<br> Last Name: " + value.last + 
                "</li>"
            );

        });

    });

});
</script>

The above JavaScript makes a call to data/data.json, ‘stringifys’ the data read in and saves it into local storage as a string. We then iterate through each contact’s first and last name, appending the data to the un-ordered list within an element with an id of contacts.

The fail promise

Recall that the done method that we have used above is technically a promise method, as the object returned by the AJAX() method (the AJAX() method is just a wrapper for our getJSON() method) implements the promise interface. Now, we are going to utilize the fail() promise method, by continuing on from our previous JavaScript, checking if local storage has any data, parsing the local storage data as a JSON object and then populating the un-ordered list accordingly. The JavaScript looks like so:

<script>
$(document).ready(function(){

    $.getJSON("data/data.json").done(function(data){

        localStorage.setItem("data", JSON.stringify(data));

        $.each(data.contacts, function(index, value){

            $("#contacts ul").append(
                "<li class='topcoat-list__item'>\
                    First Name: " + value.first + "<br> Last Name: " + value.last + 
                "</li>"
            );

        });

    }).fail(function(){

        if(localStorage.length != 0){

            var localData = $.parseJSON(localStorage.getItem("data"));

            $.each(localData.contacts, function(index, value){

                $("#contacts ul").append(
                    "<li class='topcoat-list__item'>\
                        First Name: " + value.first + "<br> Last Name: " + value.last + 
                   "</li>"
                );

            });

        }

    });

});
</script>

Now, when we load this up in our local host we can see that our data is being read in as expected and if we go into our code and change the name of the data.json file to something that doesn’t exist, we still are able to read in our data, utilizing local storage.

Here is the final product: Local Storage Application

I hope you have enjoyed this tutorial as much as I have writing it.

For more HTML5 material, check out my online course - HTML5 Mobile App Development for Beginners.

You can download the source code here.

0 comments


Or enter your name and Email
No comments have been posted yet.