Home » HTML5 » HTML5 Local Storage Example

About Arindam Chattopadhya

Arindam Chattopadhya
Arindam has completed Masters in Information Technology. His expertise includes enterprise applications architecture, application integration, legacy connectivity, user interface engineering, systems analysis and distributed systems architecture and design. He has hand-on expertise on Java EE , web technology and mobile application development.

HTML5 Local Storage Example

Introduction

HTML5 local storage allows web applications to store values locally in the browser and can survive the browser session, just like cookies. Unlike cookies that need to be sent with every HTTP request, thereby affecting website performance, local storage data as information is never transferred to the server.

Want to be a HTML5 Ninja?

Subscribe to our newsletter and download the HTML5 Programming Cookbook right now!

In order to get you prepared for your HTML5 development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

 

Additionally, cookies allow you to store only 4K of data per domain, while the local storage allows you at least 5 MB per domain.Local storage offers a simple key – value store, like a hash table object and comes in two flavors:

  • Session Storage: stores data for one browser session and is available till the browser/browser tab is closed. Popup windows opened from the same window can see session storage, and so can iframes inside the same window. However, multiple windows from the same origin (URL) cannot see each other’s session storage.
  • Local Storage: stores data with no expiration date. The data is available to all windows with the same origin (domain) even when the browser/browser tabs are reopened or closed.

Local storage is supported in the following browsers:

  • Internet Explorer 8+
  • Firefox
  • Opera
  • Chrome
  • Safari

In both the cases, please note that the storage data will not be available between different browsers.

We will create a simple shopping list example using local storage as shown below:

HTML Storage

HTML Storage

Local Storage

We will add the external javascript and stylesheet reference in the HTML header .


<head>
<title>HTML5 localStorage Example</title>
<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML,CSS">
<meta name="author" content="WebCodeGeeks.com">
<script src="Storage.js"></script>
<link rel="stylesheet" href="StorageStyle.css">
</head>

We will call the java script function doShowAll() in onload() event to a check for browser compatibility and to dynamically draw the table that displays storage name/value pair.

<body onload="doShowAll()">

In the CheckBrowser() function, we would like to check if the browser supports HTML5 storage or not. There are few ways to do it. We will use the default API  to check for the browser compatibility. Alternately, we could have used open source libraries, like Modernizr, that help us to detect the browser support for HTML5 and CSS features.

function CheckBrowser() {
    if ('localStorage' in window && window['localStorage'] !== null) {
        // we can use localStorage object to store data
        return true;
    } else {
             return false;
    }
}

Inside the doShowAll() if the CheckBrowser() function evaluates to true we will dynamically create the table for Shopping list during the page load . You can iterate the keys (property names) of the key-value pairs stored in the local storage, like this

   for (i = 0; i <= localStorage.length - 1; i++) {
            key = localStorage.key(i);
            list += "<tr><td>" + key + "</td>\n<td>"
                    + localStorage.getItem(key) + "</td></tr>\n";
        }

Based on the storage value, draw the table dynamically to display the key/value pair stored in local Storage.

function doShowAll() {
    if (CheckBrowser()) {
        var key = "";
        var list = "<tr><th>Name</th><th>Value</th></tr>\n";
        var i = 0;
        for (i = 0; i <= localStorage.length - 1; i++) {
            key = localStorage.key(i);
            list += "<tr><td>" + key + "</td>\n<td>"
                    + localStorage.getItem(key) + "</td></tr>\n";
        }
        if (list == "<tr><th>Name</th><th>Value</th></tr>\n") {
            list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
        }
        document.getElementById('list').innerHTML = list;
    } else {
        alert('Cannot store user preferences as your browser do not support local storage');
    }
}

We create a separate div element to capture the user inputs and submission. We attach the corresponding JavaScript function in the onClick event for the buttons.

<div id="PlayArea">
      <table>
            <tr>
                 <td><b>Item:</b><input type=text name=name></td>
                 <td><b>Quantity:</b><input type=text name=data></td>
             </tr>
             <tr>
                    <td>
                        <input type=button value="Save"   onclick="SaveItem()">
                        <input type=button value="Modify" onclick="ModifyItem()">
                        <input type=button value="Remove" onclick="RemoveItem()">
                     </td>
             </tr>
        </table>
</div>

Inside our style sheet we have formatted the div information as follows.

#PlayArea {
    border: 1px dotted blue;
    padding: 6px;
    background-color: #ccc;
    margin-right: 50%;
}

You can set properties on the localStorage object just like with a normal JavaScript object. Here is an example on how we can set the local storage property myProperty to the value myValue.

localStorage.myProperty = "myValue";

You can delete local storage property like this.

delete localStorage.myProperty;

Alternately use the following methods to access the localStorage

localStorage.setItem ('propertyName', 'value');
localStorage.getItem ('propertyName');
localStorage.removeItem ('propertyName');

For saving the key/value pair capture the value of the corresponding javascript object and call the .setItem method

function SaveItem() {
    var name = document.forms.ShoppingList.name.value;
    var data = document.forms.ShoppingList.data.value;
    localStorage.setItem(name, data);
    doShowAll();  
}

To fetch an existing key/value pair we will use the .getItem method

function ModifyItem() {
    var name = document.forms.ShoppingList.name.value;
    document.forms.ShoppingList.data.value = localStorage.getItem(name);
    doShowAll();
}

We will use the .removeItem method to delete from the storage.

function RemoveItem() {
    var name = document.forms.ShoppingList.name.value;
    document.forms.ShoppingList.data.value = localStorage.removeItem(name);
    doShowAll();
}

There is another method for local storage that allows you to clear the entire local storage.We have called the ClearAll() function in the onClick   event of the “Clear” button.

<input type=button value="Clear" onclick="ClearAll()">

We have used the clear method to clear the local storage as shown below.

function ClearAll() {
    localStorage.clear();
    doShowAll();
}

Session Storage

The sessionStorage object works in same way as the localStorage. You can substitute the above example with sessionStorage object  to persist the data only for the session. Once the user closes the browser window, the storage will be cleared. To summarize, the API for localStorage and sessionStorage is exactly the same, and allows you to use the following methods:

  • setItem(key, value);
  • getItem(key)
  • removeItem(key)
  • clear()
  • key(index)
  • length

Key points

  • The browser by default allows 5 MB of storage per domain . QUOTA_EXCEEDED_ERR is the exception that will get thrown if you exceed your storage quota of 5 megabytes. You might want to put a try, catch block to catch the specific error.
  • The localStorage and sessionStorage object by default only support string name/value storage. If you want to store arrays or objects into local storage use JSON.stringify to store the value and JSON.parse to retrieve the value.
  • In order to keep track programmatically of when the storage area changes, you can trap the storage event. The storage event is fired on the window object whenever you insert, update or delete a session or local storage property. The storage event is only emitted in other browser windows than the one that inserted, updated or deleted the session or local storage objects which means that for local storage, events are visible to all other windows open with the same origin, including pop up windows and iframes while for session storage events are only visible in pop up windows and iframes.
  • The  key name should be unique for each domain.

Download the Source Code

This was an example of HTML local storage.

Download
You can download the full source code of this example here: HTMLStorage

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

 

6 comments

  1. This is a great example! I love it! Can you please update or add code to write table data to a local file?

  2. THis works great,

    How do I modify the js so that it can work on several forms in one html file?
    Right now it works only on one form group.

    Thanks,

    Ric

  3. This is a great tutorial. I was wondering how to add more input fields and to attach a remove and edit button for each saved row instead of the way you have it?

  4. great example but the doShowAll seems to be showing all the storage items not just the ones from this example? How would I mod this to only call the name/data pair from storage?

  5. if we have 3 or more columns then how to proceed

  6. if we have 3 or more columns then how to proceed

Leave a Reply

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

*

Want to take your WEB dev skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • PHP Programming Cookbook
  • jQuery Programming Cookbook
  • Bootstrap Programming Cookbook
  • Building WEB Apps with Node.js
  • CSS Programming Cookbook
  • HTML5 Programming Cookbook
  • AngularJS Programming Cookbook