Notice: Undefined index: order_next_posts in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 194

Notice: Undefined index: post_link_target in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 195

Notice: Undefined index: posts_featured_size in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 196

Working with HTML5 localStorage

Discover how to use HTML5’s new method to store data locally in the browser

We’re sure you have all heard about how great HTML5 is, but how familiar are you with one of its awesome features, localStorage? It’s been around for a while, but many websites and web applications seem to be reluctant to adopt this new functionality.

LocalStorage allows any web application to store data within the browser and retrieve it seamlessly, even if the browser is closed and restarted. Many of you may now be thinking, ‘hmm isn’t this the same as cookies, which have been around since the dawn of the internet?’ The answer is no. LocalStorage is in fact very different. For starters it typically allows for a whopping 5MB of storage space per domain and is primarily used only at the client side. Cookies are sent in the headers of an HTTP request and are usually used server-side. Plus, localStorage data never expires unless the browser cache is cleared. It also uses a key/value paired system for storing the data. One of many ways you could implement localStorage is by saving form data as the user enters it. Imagine you have a multi-page form which may take a while to fill out – if the user were to go away, restart the browser and return to the form, it could remember all the data previously entered, thus increasing conversion rates.


Create your HTML

For this tutorial we will simply need a single html file with some simple styling. Remember to include jQuery as this will make life easier later in the tutorial. Make sure you dynamically include it from an external server to save your own overheads.

001 <!DOCTYPE html ><html><head>
 002 <meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1”>
 <title>Local Storage Tutorial</title>
 <link href=”style.css” rel=”stylesheet” type=”text/css” />
 003 <script type=”text/javascript” src=”http://ajax.googleapis.

Give the page some style

We are mainly interested in how the JavaScript API works with localStorage, but hey, everyone likes a bit of colour right? So lets introduce some style to our page.

Build a form

Ok, there are some important things to mention here. Note the ID of the form. This will be used later when we want to find out what fields are contained within the form. We also have an empty div with an ID of message. This will be used when we want to tell the user we have stored data.

001 <form id=”localStorageForm” method=”post” action=””>
 002    <label>First Name</label><input type=”text”  id=”firstname” name=”firstname” value=”” class=”input” />
 003    <label>Surname</label><input type=”text” id=”surname” name=”surname” value=”” class=”input” />
 004   <label>Email</label><input type=”text” id=”email” 007name=”email” value=”” class=”input” />
 005    <label>Telephone</label><input type=”text” id=”telephone” name=”telephone” value=”” class=”input” />    
 006   <input type=”submit”  class=”submit”>        
 007   </form>

Browser support

So which browsers actually support local storage? Well its the same story with many of HTML5’s new features, which means pretty much every modern browser – and that even includes internet explorer! Here is the breakdown: Internet Explorer 8+, Firefox 3.5+, Safari 4.0+, Chrome 4.0+, Opera 10.5+, iOS 2.0+, and Android 2.0+.

Browser Fallback

It is more than likely that there will be a whole range of users visiting your website, so it is important to cater for everybody’s needs. You must remember that not everyone is savvy enough to update their browsers so they will need to make sure you have considered these people too when using new technologies. An easy way of detecting whether a user has the ability to use localStorage is simple. The code below will allow you to test if the browser has localStorage capabilities.

001 function hasLocalStorage() {
 002    if (localStorage)
 003        return “Local Storage: Supported”;
 004 else
 005        return “Local Storage: Not Supported”;

Store some data

We want to save the user’s input as they begin to complete the form. An easy way to achieve this is to use jQuery to detect when a keyup action occurs. Then we can start assigning data to a unique identifier (known as a key) for each form field. We can do this by giving every form field a class called ‘input’ and listening for a keyup action on anything that has that class associated with it. Once we have detected some input from the user we can start storing some data.

001$(‘.input’).keyup(function () {
 002    localStorage.setItem(“savedData”, “true”);
 003      localStorage[$(this).attr(‘name’)] = $(this).val();

How it works

LocalStorage is basically a persistent key-value store within the browser. It has a full JavaScript API to set/get/remove data and events to track changes. We just created a key and assigned some data to it. Its that simple! You can do this by typing literally one line of code:

001 localStorage.setItem(“mykeyname”, “This is my stored data”);
 002 if you then wanted to retrieve the data we saved, and store it in a variable for later use, you could do so by simply writing:
 003 var mydata = localStorage.gettem(mykeyname);

Naming your keys

Deciding what to name your keys can be a very important factor. Key names such as ‘name’ or ‘email’ can be a bit too common and lead to confusing results. Including a prefix that relates to your site can be a good idea. I would suggest something like: re-email or re-name. This will make it a lot easier to handle and clear your data.

Overwriting keys

Another helpful feature when using localStorage is the way it allows you to overwrite the value associated with a key using the same method it was created with in the first place. This is nice to know as you don’t have to worry about any errors being thrown. Be careful though, as it is easy to overwrite a keys value when using localStorage on different sections of your site. Make sure every key has a unique name otherwise you may get unexpected results. When getItem() is called with a non-existent key it will simply return null rather than throw an exception.

Reading stored data

Reading stored data is just as easy as saving it. Because we have given our form an ID of localStorageForm, we can use this to our advantage by using jQuery’s serializeArray function. A new array will then be created and each array key will have the same name as each of the form elements. This makes life easy, as we know that each localStorage key name already matches that of the form fields.

001 var data = $(“#localStorageForm”).serializeArray();
 002 $.each(data, function(i, obj) {
 003 $(“[name=’” + +”’]”).val(localStorage.getItem(obj.

Add a Clear data button

Not only do we want to store data, but we may actually wish to delete it too. This can be done by adding a button that calls a JavaScript function to clear any stored data we already have. This can be achieved using the localstorage.clear();.

001 $(‘#clearData’).click(function() {
 002 localStorage.clear();
 003 window.location.reload() });

Use caution

It is worth noting that using the clear() function will wipe all stored data associated with the domain it is called from. There may be times where you want to remove a piece of data from a specific key. This can be done using the remove key method.

001 localStorage.removetem(mykeyname);

Test your code

Now we have code in place that will handle storing the data, we can start to fill out our form fields. Note that every time you press a key the name of the form element you are tying data into is recorded as the localStorage key name. The value then assigned to this key is the value of the form element. This value is updated every time you press a key.

Feedback to the user

Remember that empty div with the ID of message we included above the form? We can now populate that div with a message to the user to let them know that the page they are currently visiting has previously saved data. The message we have used is ‘This form has saved data!’, as you can see from the image above. However, The message can be customised to say whatever you choose. We can detect whether or not we have saved data by checking if a value has been assigned to the savedData key.

Show your saved data

Okay, lets retrieve the saved data by looping over each form field to see if there is a localStorage key with the same name. If there is, then we can build a string that will include this saved data and output it to the screen.

001 if (localStorage.getItem(“savedData”) == “true”) {
 002 var data = $(“#localStorageForm”).serializeArray();
 003 var savedData = ‘
This form has saved data!
 004 $.each(data, function(i, obj) {
 005 if (localStorage.getItem(
 006 savedData = savedData + ‘
’ + + ‘ = ‘
 007 + localStorage.getItem( + ‘
 008 document.getElementById(‘message’).innerHTML = savedData;

Give it a go

Now that we have a way of telling the user if we have previously stored data available, we can test out the form. Try typing some data into the form, then close and re-open the browser window. Voila! You will see that the form automatically loads the saved data and the message div container above the form displays what you had entered!

Other uses

In essence you could use localStorage every time you need to save the current state of a webpage. You may want to save the state of your widgets and in theory you could store entire blocks of HMTL. Many applications allow you to save their current state so it is good news that websites can now follow suit. Mobile devices can benefit from this technology as they often suffer from connectivity issues, meaning that data no longer has to be lost.

Final words

It is important to remember that localStorage is not a replacement for cookies. Yes, cookies have their limitations (the 4KB maximum storage size being one of them), but they will continue to be a critical part of your web applications despite the introduction of this newer technology. It is important not to be put off of embracing these new technologies that we are presented with, as that will only slow the evolution of the web. Instead, why not start using these little handy functions next time you are building something or working on a project. This is result in a more feature-rich user experience for your users, which can only be a good thing.