HTML5 Storage
Save. Clear. Print. HTML5 local storage.
by Edward Tanguay
HTML
Store text: <input type="text" placeholder="something to store" id="inputString" />
<button onclick="saveStatusLocally()">store</button>
<button onclick="readStatus()">print</button>
<button onclick="clearStorage()">clear storage</button>
<hr/>
<div id="content"></div>
CSS
body {
margin:20px;
}
h1 {
font-size: 2em;
}
h1:hover {
cursor: pointer;
color: #f00;
}
h1:active {
color:#555;
}
#content {
font-size: 1.5em;
font-family: courier;
}
input {
outline: none;
}
JavaScript
var stores = Array();
var inputField = document.getElementById('inputString');
function clearStorage() {
stores = Array();
localStorage.clear("database");
document.getElementById('content').innerHTML = "storage cleared.";
}
function saveStatusLocally() {
var stringToSave = inputField.value;
if ((stringToSave == null) || (stringToSave == "")) {
document.getElementById('content').innerHTML = "nothing to store.";
} else {
stores.push(stringToSave);
inputField.value = "";
window.localStorage.setItem("database", stores.join("|"));
document.getElementById('content').innerHTML = "data stored.";
setTimeout(function() {
document.getElementById('content').innerHTML = "";
}, 1000);
}
}
function readStatus() {
if (window.localStorage.getItem("database") == null) {
document.getElementById('content').innerHTML = "nothing stored.";
} else {
document.getElementById('content').innerHTML = window.localStorage.getItem("database");
}
setTimeout(function() {
document.getElementById('content').innerHTML = "";
}, 2000);
}