Cookie Monster Would Be Disappointed

Using localStorage or sessionStorage would disappoint Cookie Monster.

My go to for a website to store data temporary was to use cookies. I would use cookies for storing user preferences, scores, shopping carts and more. Cookies can be a problem though as many people stop excepting cookies and they are difficult to manage.

Now I use either localStorage or sessionStorage. The difference of syntax is subtle, but the usage is very different. Both of these is a good replacement for cookies which would disappoint Cookie Monster.

If I am creating a scoreboard for a game; I often use localStorage. I like more scoreboards to persist for a long period of time event after the browser is closed. If I am creating a shopping cart; I often will use sessionStorage so that the shopping cart persists during the usage of the site, but is discarded when the user closes the browser. With localStoarge it is assumed the user wants to maintain the data for a long time. With sessionStorage it is assumed the data is not wanted when the user is done their browser.

To demonstrate the similarity in syntax and difference in usage, I have created the code below. One must try in order to see the difference.

localStorage – keep long term

 // Initialize Scoreboard of Correct and Incorrect Values  
 if (typeof localStorage['correct'] == 'undefined') { localStorage['correct'] = 0; }  
 if (typeof localStorage['notcorrect'] == 'undefined') { localStorage['notcorrect'] = 0; }  

 // Increment Value  
 var iCorrect = parseInt(localStorage['correct']);  
 iCorrect++;  

 // Update Display and storage  
 $("#iscorrect").html(iCorrect);  
 localStorage['correct'] = iCorrect;  

sessionStorage – keep temporary

 // Initialize Scoreboard of Correct and Incorrect Values  
 if (typeof sessionStorage['correct'] == 'undefined') { sessionStorage['correct'] = 0; }  
 if (typeof sessionStorage['notcorrect'] == 'undefined') { sessionStorage['notcorrect'] = 0; }  

 // Increment Value  
 var iCorrect = parseInt(sessionStorage['correct']);  
 iCorrect++;  

 // Update Display and storage  
 $("#iscorrect").html(iCorrect);  
 sessionStorage['correct'] = iCorrect;  

The following browsers will support sessionStorage and localStorage
FireFox 3.5+
Chrome 4.0+
IE 8.0+
Safari 4.0+

Andrew Pallant (@LdnDeveloper) has been a web, database and desktop developer for over 16 years. Andrew has worked on projects that ranged from factory automation to writing business applications. Most recently he has been heavily involved in various forms for ecommerce projects. Over the years Andrew has worn many hats: Project Manager, IT Manager, Lead Developer, Supervisor of Developers and many more - See more at: http://www.unlatched.com/#sthash.8DiTkpKy.dpuf

Posted in jQuery, Web Tagged with: , , , ,