LDNDeveloper

Andrew Pallant

Software & Web Developer


Donate To Support My Blog Donate if this post helped you. Coffee money is always welcomed!




Cookie Monster Would Be Disappointed

Physical Link: 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+

The post Cookie Monster Would Be Disappointed appeared first on Software Developer In London.

Author:
Categories: jQuery, Web, Cookies, HTML5, localStorage, sessionStorage


Google | humanstxt.org | Andrew Pallant's Blog Site
©2017 LdnDeveloper