Tutorial: HTML5 Local Storage

HTML 5 Local Storage

Until HTML5 came along, storing data on the client side was always a total hack. Now it is remarkably easy and it works consistently across all modern browsers.

I’ll demonstrate how to do it by creating a dummy application for saving user preferences. I wrote this demo app as a Symfony bundle. You can download the source code from Git. If you’re not developing with Symfony, the files you want to look for are Resources/views/Default/index.html.twig and Resources/public/js/html5storage.js.

Here’s what the application should look like, if you are loading the css and everything.

Tutorial: HTML 5 Storage Screenshot

The index.html.twig loads a form that looks like this.

<p>Enter colors as just the hex code without the pound sign.</p>

<form id="user-prefs">
    <fieldset><legend>Background Color</legend><input id="bgcolor" name="bgcolor" type="text" value="" /></fieldset>
    <fieldset><legend>Foreground Color</legend><input id="fgcolor" name="fgcolor" type="text" value="" /></fieldset>
    <fieldset><legend>Font</legend><input id="font" name="font" type="text" value="" /></fieldset>
    <button id="submit" type="submit">Save Changes</button>
</form>

The real work happens in the html5storage.js, which looks like this.

$(document).ready(function() {
    $('#user-prefs input').change(function(data) {
       savePrefs(); 
    }).keypress(function(evt) {
        if (evt.which === 13) {
            evt.preventDefault();
        }
        savePrefs();
    });
    loadPrefs();
});

function savePrefs() {
    prefs = ['bgcolor', 'fgcolor', 'font'];
    for (var i = 0; i < prefs.length; i++) {
        save(prefs[i], $('#' + prefs[i]).val());
    }
    loadPrefs();
}

function loadPrefs() {
    $('#bgcolor').val(recall('bgcolor'));
    $('body').css('background-color', '#' + recall('bgcolor'));
    $('#fgcolor').val(recall('fgcolor'));
    $('body').css('color', '#' + recall('fgcolor'));
    $('#font').val(recall('font'));
    $('body').css('font-family', recall('font'));
}

function supportsLocalStorage() {
    if (Modernizr.localstorage) {
        return true;
    } else {
        return false;
    }
}


function recall(key) {
    if (!supportsLocalStorage()) return;
    return localStorage['tutorialhtml5storage.' + key];
}
    
function save(key, value) {
    if (!supportsLocalStorage()) return;
    localStorage['tutorialhtml5storage.' + key] = value;
    return true;
}

Those last three functions are the only ones that interact at all with the HTML5 local storage container. The HTML 5 local storage stores a very basic key:value set of data. It’s basically an associative array, or in Perl they called them hashes.

The localStorage variable is actually an object, but because this is Javascript, we can interact with it like it’s an array. It’s just easier to work with it as an array when creating the storage keys. I’m using tutorialhtml5storage as my namespace in the local storage container. That prevents my application from stepping on another application’s proverbial toes (that other application must be from the same origin to read this application’s localStorage, unlikely but possible depending on how your environment is configured).

The function supportsLocalStorage just checks to make sure the browser is capable of saving data locally. I’m doing this with Modernizr because it’s just a great tool to use and everyone should use it, even for small stuff.

The other two functions, recall and save, do pretty much what it sounds like they do. The save function saves one piece of data to local storage. The recall function pulls up one piece of data from local storage.

The other two functions, loadPrefs and savePrefs, just support the demo application by calling save and recall and updating the user interface accordingly.

Now before you go too hog wild with HTML5 local storage, currently browsers limit you to 5 megabytes of space. And while the data is protected in terms of same origin policies, the data is still stored on the user’s computer and so it’s outside of your server’s environment and control. Just be mindful of putting personal and private data in local storage.

Tip Jar

If you think what I’m publishing here is worth more than nothing and you want to see me keep publishing, leave a tip.

When I bartend, I get a buck for pouring someone a beer, the shit I’m doing here is worth at least a dollar.

And no, I don’t want to sell ads.

Share Button