Basic use of Local Storage

Exclusive offer: get 50% off this eBook here
Instant HTML5 Local Storage How-to [Instant]

Instant HTML5 Local Storage How-to [Instant] — Save 50%

Over 15 recipes to take advantage of the HTML5 Local Storage standard book and ebook.

$12.99    $6.50
by Alex Libby | April 2013 | Web Development

In this article by Alex Libby, the author of the book, Instant HTML5 Local Storage How-to, we will discuss about HTML5 Local Storage.

When using HTML5 Local Storage, there are two types that you can use—local storage and session storage. We'll begin by looking at the former first, using a simple form as the basis for our article.

(For more resources related to this topic, see here.)

Getting ready

For this article, all you need is your browser and favorite text editor.

How to do it...

Perform the following steps:

  1. Let's begin with creating a blank document in your text editor. Then, add the following code and save it as a test localdemo.html:

    <!DOCTYPE html> <html> <head> <script src = "http://code.jquery.com/jquery-1.8.1.min.js"></script> <script type="text/javascript"> </script> </head> <body> </body> </html>

  2. In between the <script> tags, add the following function. This copes with storing the information within the browser.

    <script type="text/javascript"> function storeItem() { var item = $('#item').val(); var items = localStorage.getItem('myItems'); if (items != null) { items = JSON.parse(items); } else { items = new Array(); } items.push(item); localStorage.setItem('myItems', JSON.stringify(items)); refresh(); } </script>

  3. We need to add another function to retrieve information and refresh the content displayed on screen. So go ahead and update the script as highlighted:

    <script type="text/javascript"> function storeItem() { var item = $('#item').val(); var items = localStorage.getItem('myItems'); if (items != null) { items = JSON.parse(items); } else { items = new Array(); } items.push(item); localStorage.setItem('myItems', JSON.stringify(items)); refresh(); } function refresh() { var items = localStorage.getItem('myItems'); var ul = $('ul'); ul.html(''); if (items != null) { items = JSON.parse(items); $(items).each(function (index, data) { ul.append('<li>' + data + '</li>'); }); } } $(function () { refresh(); }); </script>

  4. We finish by adding a basic form—while the purists amongst you will notice that it doesn't have all of the proper forms of tag, it is enough to illustrate how this demo works. Add the following code snippet, just above the closing </body> tag:

    Enter item: <input type="text" id="item" /> <input type="button" value= "store" onclick="storeItem()" /> <br /> <ul></ul>

  5. Crack open your browser and preview the results. Here's a screenshot of what you should see, with some example values already entered:

How it works...

Now we've seen Local Storage in action, let's take a look at how it works in detail.

HTML5 Local Storage works on the principle of named key/value pairs, where you store information using a named key and retrieve it by calling that named key. Everything is stored locally on the user's PC; it cuts down the need to retrieve information from the server, thereby acting as a form of caching.

You may have noticed that we've used jQuery in this article—basic use of LocalStorage (and SessionStorage) doesn't necessarily need jQuery; you could use pure JavaScript if you prefer. It all depends on your requirements; if you are already using jQuery in your pages, for example, you may prefer to use this over JavaScript. (You will see I have used a mix of both throughout this book, to show you how you can use either jQuery or JavaScript).

In this article, we've used jQuery to reference LocalStorage; if you take a look at the code, you will see two lines of particular importance:

  • var items = localStorage.getItem('myItems');

  • localStorage.setItem('myItems', JSON.stringify(items));

These two handle the retrieval and setting of values respectively. In this demo, we begin with either fetching the contents of any existing stored information and inserting them into an array, or creating a new one, if nothing exists within the store. We then use JSON. stringify() to convert information from the form into a string, push this into the storage, and then refresh the page so that you can see the updated list. To get the information back, we simply repeat the same steps, but in the reverse way.

The beauty of using JSON as part of storing information in this way is that you are not entirely limited to just plain text; you can store some other things in the LocalStorage area, as we will see later in this book.

There's more...

By now, you will start to see that using Local Storage works very much in the same way that cookies do—indeed some people often refer to Local Storage as "cookies on steroids". This said, there are still some limitations that you need to be aware of when using Local Storage, such as the following:

  • Local Storage will only support text as a format and is set to a suggested arbitary limit of 5 MB, although this is inconsistent across browsers.

  • If you exceed this, the QUOTA_EXCEEDED_ERR error is thrown. At the time of writing this book, there is no support built in for requesting more space. Some browsers such as Opera will allow the user to control each site's quota, but this is a purely userbased action.

  • Web Storage is no more secure than cookies; although use of the HTTPS protocol can resolve a lot of security issues, it is still up to you as a developer to ensure that sensitive information (such as passwords) is not sent to or stored locally on the client using Web Storage.

With careful use, we can take advantage of the ability to store relevant information on a user's PC, and avoid the need to push it back to the server. Once the information has been stored, there will be occasions when you will need to view the raw information from within your browser—this is easy enough to do, although the method varies from browser to browser, which we will see as part of the next article.

Summary

In this article we discussed basic use of HTML5 Local Storage.

Resources for Article :


Further resources on this subject:


Instant HTML5 Local Storage How-to [Instant] Over 15 recipes to take advantage of the HTML5 Local Storage standard book and ebook.
Published: March 2013
eBook Price: $12.99
See more
Select your format and quantity:

About the Author :


Alex Libby

Alex Libby is from an IT support background. He has been involved in supporting end users for the last 15 years in a variety of different environments, and currently works as a Technical Analyst, supporting a medium-sized SharePoint estate for an international parts distributor, based in the UK. Although Alex gets to play with different technologies in his day job, his first true love has always been with the Open Source movement, and in particular experimenting with CSS/CSS3 and HTML5. To date, Alex has written five books based on jQuery, HTML5 Video, and CSS for Packt Publishing, and has reviewed several more (including one on Learning jQuery). jQuery UI 1.10: The User Interface Library for jQuery is Alex's sixth book with Packt Publishing.

Books From Packt


HTML5 Canvas Cookbook
HTML5 Canvas Cookbook

HTML5 Games Development by Example: Beginner’s Guide
HTML5 Games Development by Example: Beginner’s Guide

HTML5 Video How-To [Instant]
HTML5 Video How-To [Instant]

 HTML5 Mobile Development Cookbook
HTML5 Mobile Development Cookbook

 HTML5 Game Development with GameMaker
HTML5 Game Development with GameMaker

HTML5 Graphing and Data Visualization Cookbook
HTML5 Graphing and Data Visualization Cookbook

Instant HTML5 Presentations How-to [Instant]
Instant HTML5 Presentations How-to [Instant]

Instant HTML5 Geolocation How-To [Instant]
Instant HTML5 Geolocation How-To [Instant]


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software