Saving Preferences with local Storage in Html5

About Saving  Preferences with local Storage in Html

The local Storage mechanism provides a very simple method for developers to persist data on the client’s machine. The localStorage mechanism is simply a name/value store built in to the web browser. Information stored in localStorage persists between browser sessions and can’t be read by other websites, because it’s restricted to the domain .AwesomeCo is in the process of developing a new customer service portal and wants users to be able to change the text size, background, and text color of the site. Let’s implement that using local Storage so that when we save the changes, they persist from one browser session to the next. When we’re done, we’ll end up with a prototype that looks like, on the following page.

Building the Preferences Form for Preferences with local Storage

Let’s craft a form using some semantic HTML5 markup and some of the new form controls you learned about in Chapter 3, Creating User-Friendly Web Forms, on page 45. W e want to let the user change the foreground color, change the background color, and adjust their font size for Preferences with local Storage.

<p><strong>Preferences</strong></p>
<form id= "preferences" action="save_prefs"
method="post" accept-charset="utf-8" >
<fieldset id="colors" class="">
<legend>Colors</legend>
<ol>
<li>
<label for="background_color"> Background color</label>
<input type= "color" name="background_color"
value="" id="background_color" >
</li>
<li>
<label for="text_color">Text color</label>
<input type= "color" name="text_color"
value="" id="text_color" >
</li>
<li>
<label for="text_size">Text size </label>
<select name="text_size" id="text_size">
<option value="16">16px </option>
<option value="20">20px </option>
<option value="24">24px </option>
<option value="32">32px </option>
</select>
</ol>
</fieldset>
<input type="submit" value="Save changes">
</form>
Saving Preferences with local Storage in Html5

Saving Preferences with local Storage in Html5

We’ll just use HTML color codes for the color.
Saving and Loading the Settings
To work with the local Storage system, you use JavaScript to access the window.localStorage() object. Setting a name and value pair is as simple as this:

localStorage.setItem("background_color" , $( "#background_color" ).val());

Grabbing a value back out is just as easy to Preferences with local Storage.

var bgcolor = localStorage.getItem( "background_color" );

Let’s create a method for saving all the settings from the form.

function save_settings(){
localStorage.setItem("background_color" , $( "#background_color" ).val());
localStorage.setItem("text_color" , $( "#text_color" ).val());
localStorage.setItem("text_size" , $( "#text_size" ).val());
apply_preferences_to_page();
}

Next, let’s build a similar method that will load the data from the local-Storage system and place it into the form fields to Preferences with local Storage

function load_settings(){
var bgcolor = localStorage.getItem( "background_color" );
var text_color = localStorage.getItem( "text_color" );
var text_size = localStorage.getItem( "text_size" );
$("#background_color" ).val(bgcolor);
$("#text_color" ).val(text_color);
$("#text_size" ).val(text_size);
apply_preferences_to_page();
}

This method also calls a method that will apply the settings to the page itself, which we’ll write next
Applying the Settings
Now that we can retrieve the settings from localStorage, we need to apply them to the page. The preferences we’re working with are all related to CSS in some way, and we can use jQuery to modify any element’s styles.

function apply_preferences_to_page(){
$("body" ).css("backgroundColor" , $( "#background_color" ).val());
$("body" ).css("color" , $( "#text_color" ).val());
$("body" ).css("fontSize" , $( "#text_size" ).val() + "px" );
}
$(function(){
load_settings();
$('form#preferences').submit(function(event){
event.preventDefault();
save_settings();
});
});

Falling  Back for Preferences with local Storage

The local Storage method works only on the latest Internet Explorer, Firefox, Chrome, and Safari, so we’ll need a fallback method for older browsers. W e have a couple of approaches. W e can save the information on the server, or we persist the preferences on the client side using cookies.
Server-Side Storage
If you have user accounts in your system, consider making the preferences page persist the settings to the user’s record in your application. When they log in, you can check to see whether any client-side settings exist and, if they don’t, load them from the server. This way, your users keep their settings across browsers and across computers. To persist to the server, simply ensure your form posts to the server— don’t prevent the default submit behavior with JavaScript if there’s no support for cookies. Server-side storage is really the only method that will work if the user disables JavaScript, because you could code your application to fetch the settings from the database and not the Preferences with local Storage hash. Also, this is the only approach you can take if you’re storing more than 4KB of data, since that’s the maximum amount of data you can store in a cookie.
Cookies and JavaScript
The tried-and-true combination of cookies and JavaScript can act as a decent fallback. Using the well-known cookie script from Quirksmode, we can build our own localStorage fallback solution.Detecting localStorage support in the browser is pretty simple. We just check for the existence of a localStorage method on the window object,Next, we need methods to write the cookies, which we’ll borrow from the Quirksmode article. Add these JavaScript functions to your script block, within the braces:

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires=" +date.toGMTString();
}
else var expires = "" ;
document.cookie = name+ "=" +value+expires+"; path=/" ;
}
function readCookie(name) {
var result = ""
var nameEQ = name + "=" ;
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0){
result = c.substring(nameEQ.length,c.length);
}else{
result = "" ;
}
}
return(result);
}

Finally, we want to make a localStorage object that uses the cookies as its back end. A very hackish example that just barely makes this work might look like this  to Preferences with local Storage:

localStorage = (function () {
return {
setItem: function (key, value) {
createCookie(key, value, 3000)
}
getItem: function (key) {
return(readCookie(key));
}
};
})();

We’re creating a cookie with an expiration date of 3,000 days from now. W e can’t create cookies that never expire, so I’m setting this to a ridiculously long time into the future. W’eve kept the basic implementation of local Storage the same from the outside. If you need to remove items or clear everything out, you’ll
need to get a little more creative. Ideally, in the near future, we can remove this hackish solution and rely only on the browser’s localStorage() methods here for Preferences with local Storage.

andcombd