HTML5 Storage

Save. Clear. Print. HTML5 local storage.

by socrates1024

HTML

<input type="text" placeholder="something to store" id="inputString" />
<h1 onclick="clearStorage()">clear storage</h1>
<h1 onclick="saveStatusLocally()">store</h1>
<h1 onclick="readStatus()">print</h1>
<div id="write"></div>

CSS

body {
    margin:20px;
}
h1 {
    font-size: 2em;
}

h1:hover {
    cursor: pointer;
    color: #f00;
}

h1:active {
    color:#555;
}

#write {
    font-size: 2em;
    color: #ff8800;
}
input {
    outline: none;
}

JavaScript

//array to store values
var stores = Array();
//input field text
var inputField = document.getElementById('inputString');

//clear the storage
function clearStorage() {
    //clear the storage
    stores = Array();
    localStorage.clear("database");
    //visually cleared
    document.getElementById('write').innerHTML = "storage cleared.";
}

// save the string
function saveStatusLocally() {
    //grab the value of the text box
    var stringToSave = inputField.value;
    if ((stringToSave == null) || (stringToSave == "")) {
        document.getElementById('write').innerHTML = "nothing to store.";
    } else {
        //push that value to the array
        stores.push(stringToSave);
        //clear the input field for visual 
        inputField.value = "";
        //print that value into the local storage named database and joing by a non-breaking space
        window.localStorage.setItem("database", stores.join(" "));
        //confirm write
        document.getElementById('write').innerHTML = "data stored.";
        //clear message after 1s
        setTimeout(function() {
            document.getElementById('write').innerHTML = "";
        }, 1000);

    }
}

// read the string
function readStatus() {
    //print the value of the local storage "database" key
    if (window.localStorage.getItem("database") == null) {
        document.getElementById('write').innerHTML = "nothing stored.";
    } else {
        document.getElementById('write').innerHTML = window.localStorage.getItem("database");
    }
}