Simply Cutting Edge
Welcome Guest [Log In] [Register]
Welcome to zetaNetwork. We hope you enjoy your visit.

You're currently viewing our forum as a guest. This means you are limited to certain areas of the board and there are some features you can't use. If you join our community, you'll be able to access member-only sections, and use many member-only features such as viewing zetaNetwork exclusive tutorials and articles, and access to our code snippets section. Registration is simple, fast, and completely free.


Click Here To Register


If you're already a member please log in to your account to access all of our features:

Username:   Password:
Add Reply
Getting Started With Local Storage
Topic Started: May 29 2011, 07:19 AM (591,178 Views)
Pro
Member Avatar
Underground Coding

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.
Attached to this post:
Attachments: localstorage.html (1.07 KB)
Pro | zetaNetwork Instructor & Admin
I Coded Most Of The Smexy Stuff You See :P
PM Me Any Questions
Need live support? Click here.
Offline Profile Quote ^
 
VoidPC
Rules
Getting Into The Groove
rawr!
Honestly, I've never heard of LocalStorage before. :P

Questions:
1. LocalStorage is used to store data more than 4KB?
2. The downside is it still hasn't been supported in some other browsers?
3. How long does a storage lasts? Can we delete if after a certain amount of time?
4. Can we read all of LocalStorage stuffs? For example: you can read cookies by:
Code:
 
document.write(document.cookie);
I'm glad you decided to use raw JavaScript
Edited by VoidPC, May 29 2011, 07:10 PM.
Offline Profile Quote ^
 
Pro
Member Avatar
Underground Coding

1. Yes
2. Any browser version below the ones I listed.
3. Only for security reasons, or when requested by the user.
4. Iterate through all the keys to read them all.
Pro | zetaNetwork Instructor & Admin
I Coded Most Of The Smexy Stuff You See :P
PM Me Any Questions
Need live support? Click here.
Offline Profile Quote ^
 
Reid
Member Avatar
Det är en fälla!
VoidPC
May 29 2011, 07:03 PM
rawr!
Honestly, I've never heard of LocalStorage before. :P

Questions:
1. LocalStorage is used to store data more than 4KB?
2. The downside is it still hasn't been supported in some other browsers?
3. How long does a storage lasts? Can we delete if after a certain amount of time?
4. Can we read all of LocalStorage stuffs? For example: you can read cookies by:
Code:
 
document.write(document.cookie);
I'm glad you decided to use raw JavaScript
1. It has a data limit of 5MiB
2. It is supported in every browser you probably care about
3. localStorage never expires because of time. It can be deleted by the user (according to the working draft; I don't think many browsers, if any at all, give this option yet). It should be kept as long as the browser has the info. It also can be deleted for "security reasons," whatever those may be.

sessionStorage, on the other hand, is deleted when the session ends. When that is, exactly, is left up to browsers. According to the working draft, sessionStorage may be deleted if data storage limits are reached. It can also be deleted for "security reasons."
4. Iterate through the keys, as Pro said.
Offline Profile Quote ^
 
Flavius
Member Avatar
Awesome Cool Dude

This taught me something. I am now gonna learn some Javascript. Thanks Pro.
Offline Profile Quote ^
 
Pro
Member Avatar
Underground Coding

You're not gonna learn some JavaScript? :P
Pro | zetaNetwork Instructor & Admin
I Coded Most Of The Smexy Stuff You See :P
PM Me Any Questions
Need live support? Click here.
Offline Profile Quote ^
 
Flavius
Member Avatar
Awesome Cool Dude

Pro
May 30 2011, 05:48 AM
You're not gonna learn some JavaScript? :P
Meant to say now :P Sorry.
Offline Profile Quote ^
 
1 user reading this topic (1 Guest and 0 Anonymous)
« Previous Topic · Tutorials · Next Topic »
Add Reply