HTML5 Local Storage
by Sub Taper
HTML
<script src="http://webninjataylor.com/library/js/plugins/polyfill.json.js"></script>
<script src="http://webninjataylor.com/library/js/plugins/polyfill.localstorage.js"></script>
<h1>HTML5 Local Storage (IE7+ w/polyfill)</h1>
<h2>Simple Set and Get</h2>
<form>The local storage value of 'sitename' is
<input type="text" value="WebNinjaTaylor" class="sitename" />and the length of the local storage is <span id="lss"></span>
</form>
<h2>To Do List</h2>
<form id="form" action="#" method="POST">
<input id="description" name="description" type="text" />
<input id="add" type="submit" value="Add" />
<button id="clear">Clear All</button>
</form>
<div id="alert"></div>
<ul id="todos"></ul>
CSS
form {
margin: 20px 0;
}
JavaScript
//.setItem('sitename',$('input').val()) vs. .sitename = $('input').val() ... shorthand doesn't work with IE7 polyfill
$('.sitename').val(localStorage.getItem('sitename'));
$('.sitename').change(function () {
localStorage.setItem('sitename', $('input').val());
});
$('#lss').text(localStorage.length);
$('#add').click(function () {
var Description = $('#description').val();
if ($("#description").val() == '') {
$('#alert').html("<strong>Warning!</strong> You left the to-do empty");
$('#alert').fadeIn().delay(1000).fadeOut();
return false;
}
$('#todos').prepend("<li><input id='check' name='check' type='checkbox'/>" + Description + "</li>");
$('#form')[0].reset();
var todos = $('#todos').html();
localStorage.setItem('todos', todos);
return false;
});
if (localStorage.getItem('todos')) {
$('#todos').html(localStorage.getItem('todos'));
}
$('#clear').click(function () {
window.localStorage.clear();
location.reload();
return false;
});