[HTML5] localStorage example

A simple localStorage example from the new HTML5 Web Storage JS API.

by ian_smithz

HTML

<script src="http://www.modernizr.com/downloads/modernizr-latest.js"></script>
<hgroup>
    <h1>My app settings</h1>
    <h2>Re-run this fiddle to see that your last choices are automatically selected.</h2>
</hgroup>

<form action="#" method="post" id="settingsForm">
    <fieldset>
        <ul>
            <li>
                <label for="settingsTheme">Visual theme</label>
                <select id="settingsTheme" name="settings[theme]" data-key="theme">
                    <option value="" selected>Default theme</option>
                    <option value="mellow-green">Mellow green</option>
                    <option value="simple-plain">Simple plain</option>
                    <option value="Sparks">Sparks!</option>
                </select>
            </li>
            <li>
                <label for="settingsFontSize">Font size</label>
                <select id="settingsFontSize" name="settings[font_size]" data-key="fontSize">
                    <option value="-3">-3</option>
                    <option value="-2">-2</option>
                    <option value="-1">-1</option>
                    <option value="" selected>Default size</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
            </li>
            <li>
                <input type="button" id="settingsForget" name="forget" value="Forget my settings" />
            </li>
        </ul>
    </fieldset>
</form>

CSS

hgroup {
    margin-bottom: 1em;
}

hgroup h1 {
    font-weight: bold;
}

hgroup h2 {
    color: #aaa;
}

JavaScript

jQuery(function($) {
    
    // Test if a feature is available before using it!
    if (!Modernizr.localstorage) {
        return false;
    }
    
    $('#settingsForm :input[data-key]').each(function() {
        var
            $this = $(this),
            key   = $this.data('key') || false;
        
        if (key) {
            $this
                // Set this field's default value to the
                // previously stored one - if any -
                .val(localStorage.getItem(key))
                // Bind to change event in order to store
                // the selection in the local storage
                .change(function() {
                    localStorage.setItem(key, $this.val());
                });
        }
    });
    
    $('#settingsForget').click(function() {
        localStorage.clear();
    });

});