Code
Code
Code

LocalStorage (HTML5)

Objective: To develop a small application to store contact information in localStorage who work in major browsers, Explorer 8, Firefox and Chrome.

The HTML5 bring lots of new features in this tutorial we will make a small application using the new functionality: localStorage.

With HTML5 part of the new features are focused to create web applications. LocalStorage property at present is the few that support both Chrome as Firefox, as IE 8, therefore I think a good starting point, to be really applicable functionality.

The object localStorage, store information linked  to the domain of the page.


localStorage.getItem(key);    //  Gets the value saved for the key in the domain of the page
localStorage.setItem(key,value); //  save a value with the key, and the domain of the page


We will use localStorage and JSON to make a very simple agenda, the idea is to create an array of names and emails, every time you modify and convert it to JSON localStorage saved in the key schedule, and each time you load Page localStorage retrieved from the JSON string and return to become an array. Thus we have an agenda persintent localStorage using the HTML5.


To get started create a form within a table to enter data:

<table>
<tbody>
<tr>
<th>Nom</th><th>Email</th><th>&nbsp;</th>
</tr>
<tr>
<td>Nom <input /></td>
<td>Email <input /></td>
<td><input /></td>
</tr>
</tbody>
</table>


To manage the application creates an object to encompass all the program logic,

  1. var gestor_agenda = {
  2.   local : {}
  3. }


We define a locally owned, access to a store where localStorage to unify access from different browsers.



To begin to define a method of initialization:

  1.     init : function(){
  2.         local = this.local = localStorage;
  3.         if(window.localStorage)local = window.localStorage;
  4.         json_agenda = local.getItem("agenda");
  5.         if(json_agenda) agenda = JSON.parse(json_agenda);
  6.         if(!agenda)agenda= new Array();
  7.         for(actual in agenda){
  8.             gestor_agenda.afegircamp("#control",agenda[actual].nom,agenda[actual].email);
  9.         }
  10.         $("td span.esborrar").live("click",gestor_agenda.esborrar);
  11.         $("#guardar").click(gestor_agenda.afegir);
  12.     },


Keeping localStorage access, whether it is defined globally, as if the property is a window objecte.
Once we have access to data stored localStorage recover, or if there is, the method local.getItem, data stored at key "agenda."
If there is data decode data in JSON, to use them in the script, if there is created an array yet.
We iterate the array with data to populate the table.
To manage events and initialize the script. Note the use of live. (api.jquery.com/live)

  1.     afegircamp : function(selector,nom,email){
  2.         $(selector).before($("" nom "" email "[delete]").data("dades",{nom:nom,email:email}));
  3.     },


This function simply adds one more row to the table with data epecificades, take this link for information for use later.

  1.     afegir : function(){
  2.         var nom = $("#nom").val();
  3.         var email = $("#email").val();
  4.         agenda.push({nom:nom,email:email});
  5.         gestor_agenda.local.setItem("agenda",JSON.stringify(agenda));
  6.         $("#email").val("");
  7.         $("#nom").val("");
  8.         gestor_agenda.afegircamp("#control",nom,email);
  9.     }


function that handles the event click on the Add button, retrieves the information that exists in the fields and stored in the localStorage while you add it to the table.

agenda.push: adds to the array.
JSON.strigify (agenda) converts the array into a JSON string.
gestor_agenda.local.setItem ovewrite  the current value.

  1.     esborrar : function(){
  2.         agenda = new Array();
  3.         var a = $(this).parent().parent().siblings();
  4.         $(this).parent().parent().remove();
  5.         a.each(function(){ 
  6.             dades = $(this).data("dades");
  7.             agenda.push(dades); 
  8.         });
  9.         gestor_agenda.local.setItem("agenda",JSON.stringify(agenda));
  10.     },


Delete the row of the table, then retrieve the information stored with the date Gilberto array to return it to store.

Issues to consider:
With Firefox and Explorer, the localStorage not work for local files, only with domains. With chrome work with local pages correctly.

All together

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <title></title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> 
 <script type="text/javascript" src="json2.js"></script>
 <script type="text/javascript">
   var agenda;
     
$(document).ready(function(){
      gestor_agenda.init();
});

var gestor_agenda = {
    local : {},

    init : function(){
        local = this.local = localStorage;
        if(window.localStorage)local = window.localStorage;
        json_agenda = local.getItem("agenda");
        if(json_agenda) agenda = JSON.parse(json_agenda);
        if(!agenda)agenda= new Array();
        for(actual in agenda){
            gestor_agenda.afegircamp("#control",agenda[actual].nom,agenda[actual].email);
        }
        $("td span.esborrar").live("click",gestor_agenda.esborrar);
        $("#guardar").click(gestor_agenda.afegir);
    },

    afegircamp : function(selector,nom,email){
        $(selector).before($("<tr><td>"+nom+"</td><td>"+email+"</td><td><span class='esborrar'>[delete]</span></td></tr>").data("dades",{nom:nom,email:email}));
    },

    afegir : function(){
        var nom = $("#nom").val();
        var email = $("#email").val();
        agenda.push({nom:nom,email:email});
        gestor_agenda.local.setItem("agenda",JSON.stringify(agenda));
        $("#email").val("");
        $("#nom").val("");
        gestor_agenda.afegircamp("#control",nom,email);
    }

    esborrar : function(){
        agenda = new Array();
        var a = $(this).parent().parent().siblings();
        $(this).parent().parent().remove();
        a.each(function(){ 
            dades = $(this).data("dades");
            agenda.push(dades); 
        });
        gestor_agenda.local.setItem("agenda",JSON.stringify(agenda));
    },


}

 </script>
 
 <style>
 table { width:600px; border: 1px thin #666666; margin:20px; }
 th { background-color:#990000; color:#FFFFFF; }
 .esborrar { cursor:pointer;}
 </style>
    </head>
  <body>
 
<table id="dades">
<tr><th>Nom</th><th>Email</th><th></th></tr>
<tr id="control"><td> Nom <input type="text" name="nom" id="nom"  /></td><td>Email <input type="text" name="email" id="email"  /></td><td><input type="submit" id="guardar" ></td></tr>
</table>
  
  </body>
</html>

Comunicatek - - La Bisbal d’Empordà - dani@comunicatek.com - About code - Legal