Multi
Multi
Vector Series - Getting Started With Local Storage
Topic Started: Thursday, 24. November 2011, 11:43 (417 Views)
Andrew
Member Avatar
ぼくたちがすべてはばか。
Quote:
 
Getting Started With Local Storage
Time: 20 Minutes
Difficulty: Easy



Local storage is one of those things that makes it so much easier to program web applications. Rather than storing data in a database on a server you can use local storage to store that data, not only is it much easier to use but local storage can also be used offline. In this tutorial we'll be going over how to use local storage while at the same time creating a simple notepad application.

The first thing you need to understand is: Why local storage? Why not cookies?

Cookies can bog down your page due to the fact that they are loaded with every page. With local storage, data is only needed when needed, when called. Cookies can also only hold up to 4 KB of data. Not enough to really be useful when you're developing large scale applications. The answer to all these problems would, of course, be local storage.

Another thing you need to understand about local storage is that it is part of HTML5. This means that not all browsers will support it but luckily for you I've compiled a list of browsers that do support it.

  • [*}Internet Explorer 8
  • FireFox 3.5
  • Safari 4.0
  • Google Chrome 4.0
  • Opera 10.5
Yes, Internet Explorer does support local storage, a huge surprise, yet a great asset to developers looking for cross-browser compatibility.

Now let's move on to using local storage. The local storage object is part of the window global object and can be accessed through localStorage. Remember, JavaScript is a case-sensitive language so remember to capitalize that "S".

As you know we're building a notepad application so we'll start by marking up the basic layout.
Code: HTML
 
<textarea id="notepad" style="margin-bottom: 4px; width: 100%; height: 200px"></textarea>
<button id="save">Save</button> <button id="clear">Clear</button>
We'll start by checking to see if the browser's current browser supports local storage.
Code: JavaScript
 
if(window['localStorage']){
//local storage is supported
}
else{
//local storage is not supported
}
Let's check to see if the user has any notes stored first and if so load the notes into the text area.
Code: JavaScript
 
if(localStorage['notes']){
var notes = localStorage['notes'];
document.getElementById('notepad').value = notes;
}
else{
document.getElementById('notepad').value = 'Example Note...';
}
You may have noticed that I am choosing to use raw JavaScript instead of a framework or library, that's because I decided to get back to the basics and use raw JavaScript. Now let's break down that block of code line by line.
Code: JavaScript
 
if(localStorage['notes']){
If an item in localStorage called notes exists. Remember that undefined, an empty string, and null returns false so this is perfectly acceptable. You can also choose to access items in localStorage via localStorage.getItem('notes'), either way is fine. Also, see "notes"? "Notes" is the what is called the "key", localStorage uses keys and not indices to store items.
Code: JavaScript
 
var notes = localStorage['notes'];
Get the value of notes if there are any and store it in a variable called notes.
Code: JavaScript
 
document.getElementById('notepad').value = notes;
Set the value of the element with the id "notepad" to notes.
Code: JavaScript
 
else{
document.getElementById('notepad').placeholder = 'Example Note...';
}
If the user has no notes set the placeholder of the element with the id "notepad" to "Example Note..." Easy enough to understand. Now let's code the part where the notes are actually saved.
Code: JavaScript
 
document.getElementById('save').addEventListener('click', function(){
var notes = document.getElementById('notepad').value;
localStorage['notes'] = notes;
alert('Note Saved!');
}, false);
Once again, I've gone back to raw JavaScript for this tutorial.
Code: JavaScript
 
document.getElementById('save').addEventListener('click', function(){
When the element with the id "save" is clicked.
Code: JavaScript
 
var notes = document.getElementById('notepad').value;
localStorage['notes'] = notes;
alert('Note Saved!');
Get the value of the element with the id "notepad" and store it in the variable notes. Then set the value of the item "notes" in localStorage to notes. The will create the item "notes" if it does not exist already. In addition to using localStorage like an array you can also use the function setItem() in the local storage object to set the value of an item:
Code: JavaScript
 
localStorage.setItem('notes', notes);
After all of that notify the user that the note was saved.

Now let's code our clear button.
Code: JavaScript
 
document.getElementById('clear').addEventListener('click', function(){
document.getElementById('notepad').value = '';
localStorage['notes'] = '';
alert('Notepad Cleared');
}, false);
Same setup as our save button except this time we're clearing our notepad.
Code: JavaScript
 
document.getElementById('notepad').value = '';
localStorage['notes'] = '';
alert('Notepad Cleared');
Set the value of the element with the id "notepad" to an empty string. Set the value of the item "notes" in localStorage to an empty string, remember an empty string will return false so when we check for any notes it will return false. Notify the user that the notepad was cleared. In addition to assigning an empty string to the item "notes" you can also remove the item itself from localStorage via the removeItem() function.
Code: JavaScript
 
localStorage.removeItem('notes');
Note: The function removeItem will not do anything if the item specified does not exist.

Now we'll just code that small part of our notepad that is processed if the user's browser can't support local storage.
Code: JavaScript
 
document.getElementById('notes').disabled = true;
document.getElementById('notes').value = 'Your browser does not support local storage!';
document.getElementById('save').disabled = true;
document.getElementById('clear').disabled = true;

Disable our notepad and display a message to the user.

Here's the final source of our notepad:
Code: HTML
 
<!DOCTYPE>
<textarea id="notepad" style="margin-bottom: 4px; width: 100%; height: 200px"></textarea>
<button id="save">Save</button> <button id="clear">Clear</button>
<script>
if(window['localStorage']){
if(localStorage['notes']){
var notes = localStorage['notes'];
document.getElementById('notepad').value = notes;
}
else{
document.getElementById('notepad').placeholder = 'Example Note...';
}

document.getElementById('save').addEventListener('click', function(){
var notes = document.getElementById('notepad').value;
localStorage['notes'] = notes;
alert('Note Saved!');
}, false);

document.getElementById('clear').addEventListener('click', function(){
document.getElementById('notepad').value = '';
localStorage['notes'] = '';
alert('Notepad Cleared');
}, false);
}
else{
document.getElementById('notes').disabled = true;
document.getElementById('notes').value = 'Your browser does not support local storage!';
document.getElementById('save').disabled = true;
document.getElementById('clear').disabled = true;
}
</script>



Some More Functions And Properties Of localStorage

  • length - Returns the number of items in the localStorage object.
  • key(n) - Returns the key of the item at index n.
  • clear() - Clears all the items in the localStorage object.



Well that's it, you can find the demo in the attachment. If you have any questions or comments feel free to post them here.


For the full article - http://s4.zetaboards.com/vector/topic/8735067/1/#new
Posted Image

Professional web design/development services.http://wildandrewlee.com/
Off
Profile
Quote
Top
 
Maddy
Member Avatar
BAMMMMM!
Outline Documentations
G E N E R A L

Documentation accepted in to the General database
Posted Image
This is a work in progress ^^

"You still talk about it? You still care about it."


Tumblr - WeHeartIt - My Things - Twitter

The List
Life
<3
Off
Profile
Quote
Top
 
1 user reading this topic (1 Guest and 0 Anonymous)
« Previous Topic · Coding & Development · Next Topic »

Welcome Guest [Log In] [Register]
Outline Live
Loading..
Loading..