Click here to Skip to main content
Click here to Skip to main content

HTML5 Web Storage (Example : TODO)

By , 1 Mar 2013
Rate this:
Please Sign up or sign in to vote.
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.

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

 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

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:

        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.

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.

 .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)

About the Author

@AmitGajjar
Software Developer (Senior) eInfoChips
India India
11/08/1984 - Born to be a Computer Engg.
##/##/2002 - Started Diploma CE from Govt. Collage
##/##/2005 - Started B.Tech CE From Nirma University
04/05/2008 - Join BuzzNx (Ahmedabad)
12/30/2010 - Jump to iGate (Gandhinagar)
08/01/2012 - Now eInfoChips (Ahmedabad)
 
I have started programming in early 2003. My first language was C. I have also created some visual Basic 6 applications. From that day i learned so many other languages like Python, Flex, DotNet, Java, PHP, MQL, Javascript, HTML5 and so many other languages. My majority work is in C#, MVC. Along with all professional work i have participated in couple of online competition. I won Ultrabook in CodeProject competition for publishing (http://www.appup.com/app-details/duo-brick-breaker). Currently i am working on PerC project. Hope i will got some success Smile | :)

Comments and Discussions

 
Questionhtml5 PinmemberErolBaba3-Nov-13 8:32 
AnswerRe: html5 Pinprofessional@AmitGajjar4-Nov-13 7:29 
Question? Pinmemberweilich12-Mar-13 7:58 
AnswerRe: ? Pinmember@AmitGajjar12-Mar-13 18:19 
QuestionIt might be a good idea to ... PinmemberDewey27-Feb-13 22:39 
AnswerRe: It might be a good idea to ... Pinmember@AmitGajjar27-Feb-13 23:09 
GeneralRe: It might be a good idea to ... PinmemberDewey28-Feb-13 17:33 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140421.2 | Last Updated 1 Mar 2013
Article Copyright 2013 by @AmitGajjar
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid