Friday, 24 January 2014

How to use local storage for JavaScript

Creating an to-do app is usually the first application you learn how to build in JavaScript but the problem with all those apps is that when you reload the page all those to-do’s are gone.
There is a simple solution though, and that’s to use local storage. The good thing about local storage is that you can save those bits of data to the user’s computer so that when they reload the page all of their todo’s will still be there and local storage is actually quite simple when it comes to saving the data and making it available on the page.

What is local storage?

Local storage is a part of web storage, which itself is part of the HTML5 specification. There are two options for storing data in the specification:
  • Local Storage: stores data with no expiration date and this is the one we will be using because we want our to-do’s to stay on the page for as long as possible.
  • Session Storage: only saves the data for one session so if the user closes the tab and reopens it all their data will be gone.
In simple terms, all that web storage does is store named key/value pairs locally and unlike cookies this data persists even if you close your browser or turn off your computer.

The HTML

If we think about a to-do list what we will need is :
  • An input to place our to-do.
  • An input button to add our to-do.
  • A button to clear all the to-do’s.
  • A placeholder unordered list where our to-do’s will be placed in list items.
  • And finally we need a placeholder div to show an alert when you try to enter an empty to do.
So our HTML should look something like this:
<section>
  <form id="form" action="#" method="POST">
  <input id="description" name="description" type="text" />
  <input id="add" type="submit" value="Add" />
  <button id="clear">Clear All</button>
  </form>
  <div id="alert"></div>
  <ul id="todos"></ul>
</section>
It’s a pretty standard placeholder HTML and with our javascript we can fill all this up with dynamic content.
Since we will be using jQuery in this example you should also include it in your HTML document.

The JavaScript

If we think about the structure of a simple to-do app the first thing we need to do is check for when the user clicks on add button and check if the input has an empty value, like so:
$('#add').click( function() {
   var Description = $('#description').val();
   //if the to-do is empty
   if($("#description").val() == '') {
    $('#alert').html("<strong>Warning!</strong> You left the to-do empty");
    $('#alert').fadeIn().delay(1000).fadeOut();
    return false;
   }
All we did was check for a click on the add button and run a simple test to check if the user filled the input with something. If not, the alert div fades in and stays for 1000ms and then fades out. Finally we return false so that the browser doesn’t read the rest of the script and still add the list item. 
The next thing we need to do is insert a list item with the value in the input and we will prepend this so that when the user adds a to-do it will always go to the beginning of the list and then save that list item to local storage, like so:
   // add the list item
   $('#todos').prepend("<li>" + Description + "</li>");
   // delete whatever is in the input
   $('#form')[0].reset();
   var todos = $('#todos').html();
   localStorage.setItem('todos', todos);
   return false;
});
As you can see it’s pretty standard jQuery and when it comes to local storage we need to save a key and a value. The key is a name we set for ourselves and in this case i just called it ‘todos’ and then we need to specify what we actually want to save, and in this case that is all the HTML that is placed inside the todos unordered list. As you can see we just grabbed that using jQuery and we finally returned false so that the form doesn’t submit and our page doesn’t reload.
Our next step is to check if we have something on local storage already saved in our machine and if we do we need to place that in the page, so since we gave our key the name todos we need to check for its existence like so:
// if we have something on local storage place that
if(localStorage.getItem('todos')) {
$('#todos').html(localStorage.getItem('todos'));
}
We used a simple if statement to check and then we merely got what we have on local storage and place that as the HTML of the to-do’s unordered list.
If you test our simple app and we reload the page we see that it’s already working and all we have left is to create the function for when the user chooses to clear all the to-do’s; when that happens we will clear all local storage, reload the page for our changes take effect, and then return false to prevent the hash in front of the url like so:
// clear all the local storage
$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});
With this done we have our app fully working. The full code looks like this:
$('#add').click( function() {
   var Description = $('#description').val();
  if($("#description").val() == '') {
    $('#alert').html("<strong>Warning!</strong> You left the to-do empty");
    $('#alert').fadeIn().delay(1000).fadeOut();
    return false;
   }
   $('#todos').prepend("<li><input id='check' name='check' type='checkbox'/>" + Description + "</li>");
   $('#form')[0].reset();
   var todos = $('#todos').html();
   localStorage.setItem('todos', todos);
   return false;
});

if(localStorage.getItem('todos')) {
$('#todos').html(localStorage.getItem('todos'));
}

$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});

Browser support

The support for web storage is pretty good for an HTML5 specification; it is supported by all the major browsers and even IE8, so the only thing you might need to be wary of is IE7 if you’re still supporting that.

Conclusion

Local storage in small apps like this can very welcome substitutes for databases. Storing small amounts of data doesn’t need to be complex.

No comments:

Post a Comment