Storing data client-side

To remember data between sessions, you cannot use JavaScript variables since those are not accessible every time a page is closed. You could set up a server.

You can store string data in a way that survives page reloads by putting it in the localStorage object. This object allows you to file string values under names (also strings), as in this example:

localStorage.setItem("username","marijn");
console.log(localStorage.getItem("username"));

//!marijn
localStorage.removeItem("username");

A value in localStorage sticks around until it is overwritten, it is removed with removeItem, or the user clears their local data.

Sites from different domains get different storage compartments. So it can only be read and overwritten by scripts on that same site.

Browsers also enforce a limit on the size of the data a site can store in localStorage, typically on the order of a few megabytes which prevents this feature from eating up too much disk space.

The following code implements a simple note-taking application. It keeps the user's notes as an object, associating note titles with content strings. This object is encoded as JSON and stored in localStorage. The user can select a note from a <select> field and change that note's text in a <textarea>. A note can be added by clicking a button.

snippet
Notes : <select id="list"></select>
<button onclick="addNote()">new</button><br>
<textarea id="currentnote"style="width:100%;height:10em">
</textarea>

<script>
var list = document.querySelector("#list");

function addToList(name) {
    var option = document.createElement("option");
    option.textContent = name;
    list.appendChild(option);
}
//InitializethelistfromlocalStorage
var notes = JSON.parse(localStorage.getItem("notes")) || {
    "shoppinglist": ""
};
for (var name in notes)
    if (notes.hasOwnProperty(name))
        addToList(name);

function saveToStorage() {
    localStorage.setItem("notes", JSON.stringify(notes));
}
var current = document.querySelector("#currentnote");
current.value = notes[list.value];
list.addEventListener("change", function() {
    current.value = notes[list.value];
});
current.addEventListener("change", function() {
    notes[list.value] = current.value;
    saveToStorage();
});

function addNote() {
    var name = prompt("Notename", "");
    if (!name) return;
    if (!notes.hasOwnProperty(name)) {
        notes[name] = "";
        addToList(name);
        saveToStorage();
    }
    list.value = name;
    current.value = notes[name];
}
</script>
Output
Notes :

The script initializes the notes variable to the value stored in localStorage or, if that is missing, to a simple object with only an empty "shopping list" note in it. Reading a field that does not exist from localStorage will yield null. Passing null to JSON.parse will make it parse the string "null" and return null. Thus, the || operator can be used to provide a default value in a situation like this.

Whenever the note data changes (when a new note is added or an existing note changed), the saveToStorage function is called to update the storage field. If this application was intended to handle thousands of notes, rather than a handful, this would be too expensive, and we'd have to come up with a more complicated way to store them, such as giving each note its own storage field.

When the user adds a new note, the code must update the text field explicitly, even though the <select> field has a "change" handler that does the same thing. This is necessary because "change" events fire only when the user changes the field's value, not when a script does it.

There is another object similar to localStorage called sessionStorage. The difference between the two is that the content of sessionStorage is forgotten at the end of each session, which for most browsers means whenever the browser is closed.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents