Click here to Skip to main content
15,867,989 members
Articles / Web Development / HTML

HTML5 Web Storage (Example : TODO)

Rate me:
Please Sign up or sign in to vote.
4.65/5 (19 votes)
1 Mar 2013CPOL5 min read 38.7K   1.8K   30   11
New HTML5 Feature : Web Storage and it's advantages with example

Browser Support

Web storage works with below browser versions, 
Google Chrome - 4+
Firefox - 3.5+
Safari - 4+
Opera - 10.5+
iOS - 3.2+
Android - 2.1+
 
Although I have not tried this above versions. This information is copied from other website. 
Introduction

You may heard about Cookies, The immediate words in your mind are "Security loophole, Plain Text Storage, Not preferable". Right ?

You are correct. there are some issues with Security when we are using Cookies. Hacker can read your personal data and temper on it. Another disadvantage with Cookies is, Storage capacity is only 4 kb. This is not enough for current applications. If your site is configured as highly secured then cookies will not work. So what should be the another solution for all new generation applications ? Any guess.... ?

Yes of course, you have already read the caption of the Article. It's Web Storage of HTML5.

In this article we are going to see some good stuff and example of Web Storage. We are developing TODO list for the individual. All the TODO data will be stored in your local browser.

Learning any new stuff with example always helps us to understand it very deeply. So here we have used TODO list example.

Image 1

Above screenshot is what we are going to develop. Let me give you basic idea about our requirement.

1) Notes should be stored and retrieved very quickly.

2) Notes should be filter with Category.

3) Notes should be color with different category

4) Notes should be removed if user wants.

Use of Web Storage:

Web storage can hold data in MBs. It can hold 2.5 to 10 MB of data depending on browsers. you can even test yourself. Although i have never tried it but some wiki documents provides such data.

Let we start with providing you basic operations like add/update/delete on web storage data. After getting idea about basic concept we will create simple TODO application as shown in above screen. We have used CSS and Javascript to make it like professional application. We will take code snippet from our example to present basic operations.

1) Add new item in Web Storage

JavaScript
var storage = JSON.parse(localStorage.getItem('ToDoList'));
           if (!storage) {
               storage = [];
               localStorage.setItem('ToDoList', JSON.stringify(storage));
           }

As you can see in above code we have used localStorage.getItem to check if 'ToDoList' key is exist in the local storage for particular browser.

Secondly, We are using JSON.parse to get array data. We need to store TODO category and information. we have used single dimensional array for datastorage. JSON.parse is used to convert array data into string repesentation. And JSON.Stringify can be used to convert array into string representation to store it back in local storage.

you need to keep it in mind that Web storage can hold only string data.

2) Update item in Web Storage

localStorage.setItem method in the first code snippet can be used to update item in the web storage. if you have existing key ToDoList in the web storage then it will update it's data specified by second parameter.

3) Remove item in Web Storage

JavaScript
var storage = JSON.parse(localStorage.getItem('ToDoList'));
storage.splice(itemId - 1, 2);
localStorage.setItem('ToDoList', JSON.stringify(storage));  

In our case we need to remove item from the array list. we have one dimensional array to store category and it's note value. category will be stored in all odd indexes while todo notes will be stored in all even indexes. We need to remove two item from array to remove particular notes.

In given example we have used splice to remove from the array. first parameter of splice define index from where we need to remove item while the second parameter defines number items we need to be removed.

And at last we have update array list. if we are not using array and if we have single key/value pair for storing in web storage then we can use removeItem method of localStorage.

Hope this information is enough to start working with web storage of html5. Now we will see the code for creating your personal todo list.

Important Code:

JavaScript
function loadNotes() {
    var storage = JSON.parse(localStorage.getItem('ToDoList'));
    if (!storage) {
        storage = [];
        localStorage.setItem('ToDoList', JSON.stringify(storage));
    }
    var displayArea = document.getElementById("displayArea");
    var currentFilter = document.getElementById("slSearchCategory").value;
    var innerDiv = "";
    for (var i = storage.length - 1; i >= 0; i = i - 2) {
        if (currentFilter == storage[i - 1] || currentFilter == "") {
            var todoColor = 'AD7460';
            switch (storage[i - 1]) {
                case 'HR':
                    todoColor = '90CA77';
                    break;
                case 'Payroll':
                    todoColor = '81C6DD';
                    break;
                case 'Sales':
                    todoColor = 'F9D654';
                    break;
                case 'Personal':
                    todoColor = 'AD7460';
                    break;
                default:
                    todoColor = 'AD7460';
                    break;
            }
            innerDiv += "<div class='displayToDo'  style='background:#" + todoColor + "'><input type='image' src='delete.png' width='15px' height='15px' onclick='removeMe(" + i + ")' /> Category : " + storage[i - 1] + " <hr /> " + storage[i] + "</div>";
        }
    }

    if (innerDiv != undefined) {
        displayArea.innerHTML = innerDiv;
    }
    else {
        displayArea.innerHTML = "";
    }

First of all we are taking all the todo that we have stored in the array called ToDoList. Once we have data we are ready to render data on the html page. we have one static div with id='displayArea'. Then for each item in the array we will iterate and check for the category of particular todo item. According to category we will assign hex color value into one variable. once we are ready with the color hex code we are dynamically creating html divs. Once we have ready html code we can set as innerHtml.

At last we have added condition to check if innerDiv value is updated with some dynamic data or not. In case of empty web storage array innerDiv value will be undefined.

JavaScript
function SaveNotes() {
            var category = document.getElementById("slSearchCategory").value;
            var todo = document.getElementById("txtToDo").value;

            if (category == "") {
                alert("Please select Category.");
                return;
            }

            var storage = JSON.parse(localStorage.getItem('ToDoList'));
            var arrayLength = storage.length;

            storage[arrayLength] = category;
            storage[arrayLength + 1] = todo;
            localStorage.setItem('ToDoList', JSON.stringify(storage));
            category = "";
            loadNotes();
            clearNote();
        } 

Above Javascript function will be called when you click on the 'Add TODO' button. We need the category and todo note as input from the dropdown list and textArea respectively. After getting data we have added validation to check if user have clicked button without selecting correct category. Once you have correct data you are ready to add new item into the web storage array. And last two steps is to load Notes again and Clear the TextArea(todo that you have entered).

We have also used some CSS3 features to display round corner div. this will really help to designer. when we do not have CSS3 we need to do a lot of work to handle such situation.

CSS
.displayToDo
       {
           -moz-border-radius: 10px;
           border-radius: 10px;
           height: Auto;
           width: 200px;
           color: #ffffff;
           float: left;
           margin: 10px;
           padding: 10px;
       }  

As you can see in the above CSS code we have displayToDo CSS class. if you have observed we are applying this CSS class to dynamically generated div. This style will be applied immediately when DOM will be updated with given innerHTML dynamic text.

Conclusion

Using HTML5, JavaScript and CSS3 we can easily develop some application that can be ready to use. We do not need database system to store. Although there are some limitation but we can at least store data very efficiently. For further information better you can download attachment and use it. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWill this support IE ? Pin
Member 103095882-Sep-16 11:34
Member 103095882-Sep-16 11:34 
AnswerRe: Will this support IE ? Pin
AmitGajjar2-Sep-16 11:37
professionalAmitGajjar2-Sep-16 11:37 
QuestionNice explanation and attachment thanks Pin
Balabb15-May-14 23:11
Balabb15-May-14 23:11 
GeneralRe: Nice explanation and attachment thanks Pin
AmitGajjar16-May-14 3:36
professionalAmitGajjar16-May-14 3:36 
Thanks
Questionhtml5 Pin
yabanci11223-Nov-13 8:32
yabanci11223-Nov-13 8:32 
AnswerRe: html5 Pin
AmitGajjar4-Nov-13 7:29
professionalAmitGajjar4-Nov-13 7:29 
Question? Pin
weilich12-Mar-13 7:58
weilich12-Mar-13 7:58 
AnswerRe: ? Pin
AmitGajjar12-Mar-13 18:19
professionalAmitGajjar12-Mar-13 18:19 
QuestionIt might be a good idea to ... Pin
Dewey27-Feb-13 22:39
Dewey27-Feb-13 22:39 
AnswerRe: It might be a good idea to ... Pin
AmitGajjar27-Feb-13 23:09
professionalAmitGajjar27-Feb-13 23:09 
GeneralRe: It might be a good idea to ... Pin
Dewey28-Feb-13 17:33
Dewey28-Feb-13 17:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.