How to Save Preferences with localStorage

, , Leave a comment

The localStorage mechanism provides a very simple method for developers to persist data on the client’s machine. The localStorage mechanism is simply a 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 you’re currently visiting. Today  I will show you how to save preference with localStorage.

See the Demo

Lets start with HTML5  Markup

The HTML

{code}<p><strong>Preferences</strong></p>

 

<form id=”preferences” action=”save_prefs”

method=”post” accept-charset=”utf-8″>

<fieldset>

<legend>Colors</legend>

<ul>

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

</ul>

</fieldset>

<input type=”submit” value=”Save changes”>

</form>{/code}

The Javascript

To work with the localStorage system, you use JavaScript to access the window.localStorage() object.

I have include jQuery from Google’s CDN.

I have created the “preference.js” file into “js” folder. All our javascript code will be here.
{code} <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>

<script type=”text/javascript” src=”js/preference.js”></script>{/code}
Above code we can place end of <tittle> tag.

Saving and Loading the Settings

{code}localStorage.setItem(“background_color” , $(“#background_color” ).val());{/code}
Grabbing a value back out is just as easy.
{code}var bgcolor = localStorage.getItem(“background_color” );{/code}
We already created the pagination.js. Add the following code into pagination.js file file.
{code}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();

}{/code}
Next, let’s build a similar method that will load the data from the local- Storage system.
{code}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();

}{/code}
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
{code}function apply_preferences_to_page(){

$(“body”).css(“backgroundColor”, $(“#background_color”).val());

$(“body”).css(“color”, $(“#text_color”).val());

$(“body”).css(“fontSize”, $(“#text_size”).val() + “px”);

}{/code}
Finally, we need to fire all of this when the document is ready.
{code}$(document).ready(function(){

load_settings();

$(‘form#preferences’).submit(function(event){

event.preventDefault();

save_settings();

});

});{/code}

Falling Back

The localStorage method works only on the latest Internet Explorer, Firefox, Chrome, and Safari, so we’ll need a fallback method for older browsers. We have a couple of approaches. We can save the information on the server, or we persist the preferences on the client side using cookies.

Server-Side Storage

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 localStorage 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. Cookies and JavaScript The tried-and-true combination of cookies and JavaScript can act as a decent fallback. We can build our own localStorage fallback solution.
{code}if (!window.localStorage){

}{/code}
Next, we need methods to write the cookies.  Add these JavaScript functions to your script block, within the braces.
{code}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);

}{/code}
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.
{code}localStorage = (function () {

return {

setItem: function (key, value) {

createCookie(key, value, 3000)

},

 

getItem: function (key) {

return(readCookie(key));

}

};

})();{/code}
In the line 4, We’re creating a cookie with an expiration date of 3,000 days from now. We can’t create cookies that never expire, so I’m setting this to a ridiculously long time into the future.

Full Javascript Code

{code}$(document).ready(function(){

 

if (!window.localStorage){

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

}

localStorage = (function () {

return {

setItem: function (key, value) {

createCookie(key, value, 3000)

},

 

getItem: function (key) {

return(readCookie(key));

}

};

})();

}

 

load_settings();

 

$(‘form#preferences’).submit(function(event){

event.preventDefault();

save_settings();

});

});

 

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();

}

 

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(){

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();

}{/code}

Styling with CSS

I have created the “Style.css” file into “css” folder. All our css styles will be here.
{code}<link rel=”stylesheet” href=”css/Style.css” type=”text/css” />{/code}

 

Above code we can place end of <tittle> tag.
{code}fieldset{

 

width: 215px;

}

fieldset ul{

list-style: none;

padding:0;

margin:2px;

}

fieldset ul li{

margin:0 0 9px 0;

padding:0;

}

fieldset input{

display:block;

fieldset select{

display:block;

}{/code}

Share this: