Having fun with HTML5 – Local Storage and Session Storage

HTML5 includes two new ways to store data on the client – local storage and session storage. Local storage has no time limit on how long the data should be kept around, session storage on the other hand (as the name suggests) stores data for only one session.

Traditionally you can store data on the client using cookies, but they are not suited for storing large amounts of data because everything gets sent back to the server on every request and hence slows down the roundtrip and making the user experience less enjoyable.

Using the new storage methods, data is only passed on when asked for and it’s therefore possible to store large amounts of data without slowing down the site. The data is also sandboxed and a website can only access data stored by itself, you can use javascript to set and get data from the relevant storage.

Browser Support Detection

A browser that supports HTML5’s local storage will have a localStorage property on the global window object, you can write your own function to check for the existence of and validity (not null) of the localStorage property, or use a third-party library like Modernizr.

Modernizr is an open source, light weight javascript library that detects support for many HTML5 and CSS3 features, when it runs it creates a global object called Modernizr. To check for local storage support, all you need to do is to check the boolean flag for local storage:

if (Modernizr.localstorage) {
    // browser supports local storage
}
else {
    // browser doesn't support local storage
}

or similarly for session storage:

if (Modernizr.sessionstorage) {
    // browser supports local storage
}
else {
    // browser doesn't support local storage
}

API

The full API specification for the localStorage and sessionStorage objects can be found here. At the time of writing, this is how the common Storage interface look:

image

Demo

I’ve put together a quick demo here to illustrate how to detect and use the local and session storage to get, set, remove and clear stored items (well, basically, covers each of the available methods on the Storage interface above).

The page itself is simple and crude, just a couple of <div> and most importantly two tables which I use to show all the key value pairs stored in the local and session storage:

image

Page Load

When the page finishes loading, I call the Modernizr object to find out if the current browser supports local and/or session storage, if not, hide the relevant <div> elements so the tables are not even shown on the page:

$(document).ready(function () {
    // hide the storage divs if browser doesn't support local storage or session storage

    if (Modernizr.localstorage && Modernizr.sessionstorage) {
        $("#detectionSpan").html("Your browser supports both local and session storage");
    } else {
        if (!Modernizr.localstorage) {
            $("#detectionSpan").html("Your browser doesn't support local storage");
            $("#localStorageDiv").hide();
        } else {
            $("#detectionSpan").html("Your browser doesn't support session storage");
            $("#sessionStorageDiv").hide();
        }
    }
    showKeys();
});
Populate Tables

The showKeys() function populates the localTable and sessionTable tables with the keys in the corresponding storage if and only if the storage type is supported by the browser:

// show the keys currently held in the local and session storage
function showKeys() {
    if (Modernizr.localstorage) {
        showStorageKeys("local", "#localTable");
    }
    if (Modernizr.sessionstorage) {
        showStorageKeys("session", "#sessionTable");
    }
}

// show the keys currently held in the specified type of storage in the specified table
function showStorageKeys(type, table) {
    // get the specified type of storage, i.e. local or session
    var storage = window[type + 'Storage'];

    // remove the rows in the specified table before we start
    $(table + " > tbody > tr").remove();

    // loop through the existing keys in the storage and add them to the TBODY element as rows
    for (var i = 0; i < storage.length; i++) {
        var key = storage.key(i);
        var value = storage.getItem(key);
        $(table + " > tbody:last")
            .append("<tr><td>" + key + "</td>" +
                    "<td>" + value + "</td>" +
                    "<td><input type='submit' value='Remove' onclick='removeItem(\"" + type + "\", \"" + key + "\")'/></td></tr>");
    }
}
Introducing the new placeholder attribute

You might have noticed that the two text boxes had placeholder text similar to that familiar search box in Firefox:

text boxes with place holder text Firefox search box

This is done using HTML5’s placeholder attribute for the <input> tag:

<input id="keyText" placeholder="Enter key"/>
<input id="valueText" placeholder="Enter value"/>

Nice and easy, eh? ;-)

Setting an item

To add a new key value pair or update the value associated with an existing key, you just have to call the setItem method on the intended storage object:

// adds a new key to both local and session storage
function setKey() {
    var key = $("#keyText").val();
    var value = $("#valueText").val();

    if (Modernizr.localstorage) {
        localStorage.setItem(key, value);
    }
    if (Modernizr.sessionstorage) {
        sessionStorage.setItem(key, value);
    }
    showKeys();
}
Removing an item

Earlier in the showStorageKeys(type, table) function, I added a row to the relevant table for each key value pair in the storage including a button with a handler for the onclick event. The handlers are created with the correct storage type (“local” or “session”) and key for the current row baked in already so that they will call the removeItem(type, key) function with the correct parameters:

// removes an item with the specified key from the specified type of storage
function removeItem(type, key) {
    // get the specified type of storage, i.e. local or session
    var storage = window[type + 'Storage'];
    storage.removeItem(key);
    showKeys();
}
Clearing all items

Finally, the ‘”Clear” buttons underneath the tables call the clearLocalKeys() and clearSessionKeys() function to remove all the key value pairs in the corresponding storage:

function clearLocalKeys() {
    clearKeys("local");
}

function clearSessionKeys() {
    clearKeys("session");
}

// clear all the held keys in the specified type of storage
function clearKeys(type) {
    // get the specified type of storage, i.e. local or session
    var storage = window[type + 'Storage'];

    // clear the keys
    storage.clear();

    showKeys();
}

So that covers all the interesting bits about the demo and all and all pretty straight forward and easy to implement, admittedly I’m a javascript novice so if you feel any of this could be done better please feel free to point out to me!

Having fun with HTML5 – Range type input

Besides the much talked about video tag, HTML5 also introduced a couple of new input types, one of which is a rather interesting range input type which basically translates to a slider bar control:

image

The range input type is currently supported by the latest versions of Safari, Chrome and Opera while other browsers such as Firefox simply treat the field as a textbox.

There are four available attributes – min, max, step and value. min and max should be self explanatory, step determines the size of each increment/decrement and value is the current value of the slider and also determines the placement of the slider when the element is loaded (if not specified, the slider will appear at the centre of the control when it’s first loaded):

<input type="range" min="0" max="200" step="5"></input>

image

<input type="range" min="0" max="200" value="0" step="5"></input>

image

I talked about the new border radius property being introduced in CSS3 in my previous blog post, and with a little JQuery I’ve put together a quick demo here of how a 400px by 400px square looks as the border radius changes.

If you look at the source of the page you will see that I added a changeBorder javascript function to handle the onchange event fired by the slider, which dynamically updates the HTML content of an internal CSS class called mySliderBarStyles using the current value of the slider control:

<input id="mySliderBar" type="range" min="0" max="200" value="0" step="5"
       onchange="changeBorder(this.value)"></input>
…
<script type="text/javascript">
    function changeBorder(newValue) {
        var newRadius = newValue + "px";
        // set the html content of the label showing the current radius value
        $("#rangeValue").html(newRadius);
        // set the style with the new radius value
        $("#mySliderBarStyles").html(
            "#myDiv { -webkit-border-radius: " + newRadius + "; }"
        );
    }
</script>
…
<style type="text/css" id="mySliderBarStyles"></style>

References:

Dive Into HTML5