W3COne of the new features that you may want to use in your line of business application is local storage. We can store data locally or use cookies.

localstorage provides a way to persist data on the client side without using cookies. The localStorage attribute provides persistent storage areas for domains. It allows Web applications to store nearly 10 MB of user data, such as entire documents or a user's mailbox, on the client for performance reasons.

This code uses both Modernizr and jQuery—Modernizr to let us know whether we need to support cookies instead of local storage and jQuery to insert HTML into the DOM to show that our local storage worked.

In the last post in this series, we showed how you can Get Started with Modernizr and Get Started with JQuery.

Detecting localstorage

You can use Modernizr to detect is localStorage is available, and if not you can fall back to good old cookie storage.

<script type="text/javascript">
     if (Modernizr.localstorage) { 
        $('#LocalStorageStatus').html('localStorage is available'); 
     }        
    else {
        $('#LocalStorageStatus').html('looks like cookies');        
    }    
</script>

And in our HTML:

<div id="LocalStorageStatus"></div>

IE8 and IE9 running in IE7 mode will support localstorage. From a user standpoint, this is probably what you want for your users. But you will want to turn off localstorage while you are testing. Open "Internet Options" for IE, go to the "Advanced" tab, and clear "Enable DOM storage" to turn off localstorage and thus test our code.

internetoptionsdisablelocalstorage_t

So we use some code to save something to local storage.

Code for localstorage

First, I’ll add some HTML with an input box whose data I’ll store.

<div id="somedata">
    <label for="yourName" title="Your Name">Your Name</label>
    <input id="yourName" type="text" onchange="SaveYourName()"/>
</div>
<div id="yoursavedname"></div>

After my code loads Modernizr, I can check to see if local storage is supported. If so, I can then use local storage or use a cookie.

I can save the data in local storage using a key, value pair using setItem(). I can then retrieve the value by using getItem().

function SaveYourName() {
    var yourName = $("#yourName").val();
    if (Modernizr.localstorage) {
        try {
            //saves to the database, “key”, “value”
            localStorage.setItem("name", yourName);
        } catch (e) {
            if (e == QUOTA_EXCEEDED_ERR) {
                //data wasn’t successfully saved due to quota exceed so throw an error
                alert('Quota exceeded!');
            }
        }

        $("#yoursavedname").append("Your name was saved:" + localStorage.getItem("name")); 
    }
    else {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + 30);
        var c_value = escape($(yourName).val()) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
        document.cookie = c_name + "=" + c_value;
        $("#yoursavedname").append("Your cookie:" + document.cookie); 
    }
}

For the purposes of demonstration, I use jQuery to insert value that I retrieve from local storage.

The code $("#yoursavedname").append() method adds the text passed as the parameter into the yoursavedname div.

And if local storage is not available, I just use a cookie.

Local Storage Methods

The following properties and methods are supported by both session and local storage objects.

  • clear. Removes all key/value pairs from the Web Storage area.
  • getItem. Retrieves the current value associated with the Web Storage key.
  • key. Retrieves the key at the specified index in the collection.
  • length. Retrieves the length of the key/value list.
  • remainingSpace. Retrieves the remaining memory space, in bytes, for the storage object.
  • removeItem. Deletes a key/value pair from the Web Storage collection.
  • setItem. Sets a key/value pair.

For More Information

See:

Next Up

We’ll build our form with some new features in HTML5 Forms.

 

Bruce D. Kyle
ISV Architect Evangelist | Microsoft Corporation

image