Tuts

Best use of Local Storage for JavaScript

Views

Localstorage-featureGenerally a to-do application is the first app that clears the hesitation of building an app using JavaScript. But the problem arises when you reload the pages of the app and all the to-do’s are vanished.

Local Storage is the simple solution to this issue. The best part about local storage is that you could store the essential data on the user’s computer. So that even if you reload the page they (to-dos) are not gone and are available at the local storage.

What Actually Is Local Storage?

Local storage is nothing but a part of web storage, which is actually used for storing the data. It can even be said as the part of HTML5 specification. Data can be stored in the specification using the two ways:

  • Session Storage: As the name suggest, the data is store for only one session. This type of data storage is impermanent as the data lost when the session is over and users closes the windows tab.
  • Local storage: Here the stored data is safe as it has no expiration date. You can say this one as reliable source of data storage.

In a simpler and clearer way, the purpose of web storage is to store values locally just alike the cookie does. Cookie preserves the data even if you turn off your system for a few days or weeks.

Understanding HTML

HTML5 To do imageSuppose creating a do-to list, let’s assume the important things that we require

  • Obviously input that need to be placed in our to-do.
  • Additionally a button to insert our to-do values
  • To clear the to-do list values, a clear button
  • A placeholder unordered list to get the items placed
  • A placeholder div to pop an alert if any empty to-do is entered

Just have a look on our HTML code

    As we are employing jQuery for this provided example so we will also be including that in our HTML document. It is a standard placeholder HTML and by using JavaScript we will full this to make fully dynamic.

     Understanding JavaScript

    Java Local Storage Using JavaScript structure in a simple to-do app, we need to test when the user clicks on the add button to insert the value. And what if the user does not fill the value. Check out the code snippet to get a clear understanding.

    $('#add').click( function() {
       var Description = $('#description').val();
       //if the to-do is empty
       if($("#description").val() == '') {
        $('#alert').html("Warning! You left the to-do empty");
        $('#alert').fadeIn().delay(1000).fadeOut();
        return false;
       }

    In this code snippet we tried to check when a user clicks on the add button. A simple test runs when the user enters the input. In case, nothing is filled as the input the alert div fades in and activates for 1000ms after this time completion it automatically fades out. If this happens, we come false and browser will not be able to read the remaining script.

    After that we will insert a complete list of item as an input value. We are doing this as when the user will insert a to-do it will go automatically to the beginning of the list and saving the list items in the local storage, which will work like:

    
       // add the list item
       $('#todos').prepend("
  • " + Description + "
  • "); // delete whatever is in the input $('#form')[0].reset(); var todos = $('#todos').html(); localStorage.setItem('todos', todos); return false; });

    Here, we are following a standard jQuery for using local storage to store a key and a value in it. The key is a name and here I’m using it by the name of to-do.

    Then the second thing is that what actually need to be stored and therefore we are using HTML inside the todo’s unordered list. Using jQuery we have finally returned with false in case the form doesn’t submit, our page will not reload.

    Thirdly we have to check if there is something already being saved on our local storage. For that we have already a key named to-do, so this is how we can check:

    // if we have something on local storage place that
    if(localStorage.getItem('todos')) {
    $('#todos').html(localStorage.getItem('todos'));
    }

    Here we have used if statement to check what we contain in the local storage and we come up with an HTML having to-do’s unordered list. For testing the simple app whether it is working fine. We first reload the page now we are creating a function so that when the user wishes to clean all to-do’s; the local storage will be cleared. Refresh the page to notice the changes. You will come up with false in order to prevent from hash being added in the url, like this:

    
    // clear all the local storage
    $('#clear').click( function() {
    window.localStorage.clear();
    location.reload();
    return false;
    });

    Once you will run this, this means your fully-fledged. The complete code will see like this:

    $('#add').click( function() {
       var Description = $('#description').val();
      if($("#description").val() == '') {
        $('#alert').html("Warning! You left the to-do empty");
        $('#alert').fadeIn().delay(1000).fadeOut();
        return false;
       }
       $('#todos').prepend("
  • " + Description + "
  • "); $('#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

    As we are using HTML5 specifications, the app will support all the popular browsers including IE8. But the ones who still like IE7 then it might be a browser compatibility problem for them.

    Conclusion

    Local storage for storing small app is the best substitute of database but storing complex data is not invited.

    About The Author

    Suren · A perfect enthusiast PRO-Blogger on TechMagz site and writing professional tech blogging contents! Have a good exposure on technology news, the latest release of gadgets, experienced WordPress designer and lovely DAD for two adorable children.


    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.