At the very start of this book, I mentioned the need to use strings to store content in Local Storage. What if I said that it was possible to store objects and arrays in Local Storage as well? You'd be right in pointing out that these are not strings. You can still store content from data objects and arrays, if you use the power of JSON to convert them, as we will see in this recipe.
For this recipe, we will need our usual text editor, as well as the code that accompanies this book. We will also need a copy of the jStorage plugin that is available from http://github.com/andris9/jStorage/raw/master/jstorage.js, as well as jQuery; you can download this from http://code.jquery.com/jquery-1.8.3.min.js (or use the link as a CDN link).
Perform the following steps, for adding objects, arrays, and TTL support to storage:
addttlsupport.html
:<!DOCTYPE html> <html> <head> <title>Getting Started with HTML5 local storage</title> <meta charset="utf-8"> <script src= "http://code.jquery.com/jquery-1.8.3.min.js"></script> <script src="jstorage.js"></script> <script type="text/javascript" src="addttlsupport.js"> </script> <link rel="stylesheet" type="text/css" href="addttlsupport.css"> </head> <body onload="load()"> <div id="myform"> <div id="results"> <b>Simple form with name and age:</b><p> <div id="gTTL"></div> </div> </div> </body> </html>
addttlsupport.css
file from the code that accompanies this book, and save it in the same location as the main HTML file.<div id="gTTL"></div> <table> <tr> <td>Name:</td> <td><input type="text" id="name"></td> </tr> <tr> <td>Age:</td> <td><input type="text" id="age"> </tr> </table> <p> <table> <tr> <td><input type="button" class="button medium gray" id="addInfo" value="Add to Storage"></td> <td><input type="button" class="button medium gray" id="getInfo" value="Get from Storage"></td> <td><input type="button" class="button medium gray" id="gTTLbutton" value="Get TTL"></td> </tr> <tr> <td><input type="button" class="button medium gray" id="saveC" value="Save complex data"></td> <td><input type="button" class="button medium gray" id="restoreC" value="Restore complex data"></td> </tr> </table>
LocalStorage
. Go ahead and add the following into a file called addttlsupport.js
, beginning with the save()
method handler:function saveInfo() { try { $.jStorage.set("name", $("#name").val()); $.jStorage.set("age", $("#age").val()); $("#name").val(""); $("#age").val(""); $.jStorage.setTTL("name", 30000); } catch (e) { if (e == QUOTA_EXCEEDED_ERR) { console.log("Error: Local Storage limit exceeds."); } else { console.log("Error: Saving to local storage."); } } }
LocalStorage
:function getInfo() { console.log("Getting your data from local storage."); $("#name").val($.jStorage.get("name")); $("#age").val($.jStorage.get("age")); }
function load() { if (typeof(Storage) == "undefined" ) { alert("Your browser does not support HTML5 localStorage. Try upgrading."); } else { console.log("Both localStorage and sessionStorage support is there."); } }
LocalStorage
.function sComplexData() { console.log("Saving complex data to local storage."); var personObject = new Object(); personObject.name = $("#name").val(); personObject.age = $("#age").val(); $.jStorage.set("person", JSON.stringify(personObject)); }
function rComplexData() { console.log("Restoring complex data from local storage."); var personObject = JSON.parse($.jStorage.get("person")); $("#name").val(personObject.name); $("#age").val(personObject.age); }
function getTTLforName() { var ttl = $.jStorage.getTTL("name"); $("#gTTL").html("TTL time for 'name' key, using simple store: " + ttl); }
<script type="text/javascript" src="addttlsupport.js"> </script> <script type="text/javascript"> $("document").ready(function() { $("#getInfo").click(getInfo); $("#addInfo").click(saveInfo); $("#gTTLbutton").click(getTTLforName); $("#saveC").click(sComplexData); $("#restoreC").click(rComplexData); }) </script>
Alex
and 38
added to LocalStorage
, using Add to Storage and the TTL value retrieved:Read through the code carefully, do you notice anything in particular? One thing may pop out. We've used JSON to convert contents into strings before storing them. The keen-eyed amongst you would notice that we have actually used the same principles within the very first recipe in this book, Basic use of Local Storage.
We begin with the usual call to jQuery, followed by one to jStorage. We then have a number of functions that are used to either save content to, or retrieve from, LocalStorage
. Our first two methods, save()
and get()
, are responsible for fetching and retrieving content from LocalStorage
; the former includes a call to .setTTL()
to set a TTL value 30000
or 30 seconds.
The next one, load()
, performs a check when loading the web page, to ensure we use LocalStorage
correctly. This is followed by sComplexData()
, which creates a data object called personObject()
, stores two values person and age within it, and then converts them into a key called person
, using JSON, before storing them in LocalStorage
. The rComplexData()
handler retrieves the same person
key, then parses it using JSON, before extracting the appropriate values and displaying them on the screen.
The keen-eyed amongst you may have noticed that the code does not include support arrays. This is deliberate; I thought I would leave this as a recipe for you to complete! A hint, it uses the same method to store the content in LocalStorage
; all you need to do is get the content into an array first.
So far, we've looked at using strings within our code, which works well. What if I say we could really turn the tables, and start to include images within LocalStorage
? Yes, you heard right, images! We'll see how we can do that as part of the next recipe.