HTML and CSS Reference
In-Depth Information
three steps are required: add the item to the list element on the page,
add the item to local storage, and finally clear the text input ready for
the next item:
function add_item() {
var new_item =
document.
getElementById('new_item');
add_listitem(new_item.value);
add_storageitem(new_item.value);
new_item.value = '';
}
This calls functions to add the item to the list on the page and to add
the same item to local storage. The function that adds an element to the
page is straightforward, using the same
DOM
scripting techniques that
everyone's been using for years with
HTML4
:
function add_item() {
var new_item = document.getElementById('new_item');
add_listitem(new_item.value);
add_storageitem(new_item.value);
new_item.value = '';
}
The interesting thing is the call to the
add_storageitem
function:
function add_storageitem(item) {
var key = new Date();
window.localStorage.setItem(
key.getTime(),item
);
}
The
localStorage
object is available from the
window
object. In this case,
you call the
setItem
method that adds the provided key-value pair to
the storage. It doesn't matter what the key is—it just has to be unique.
If you call
setItem
with a key that already exists, it will overwrite the
previously stored item, so the current time in milliseconds is used. The