HTML5 and CSS3, Second Edition

(singke) #1
We’ll use HTML color codes for the colors, and we’ll use the HTML5 color type
for the fields. We’ll also add a tiny bit of CSS to style the form:

html5_localstorage/stylesheets/style.css
formol{
list-style:none;
margin:0;
padding:0;
}

formli{
margin:0;
padding:0;
}

formli label{ display:block;}

This is enough to get the prototype ready. Now let’s persist the changes we
make on the form.

Saving and Loading the Settings


To work with the localStorage system, we use JavaScript to access the window.local-
Storage() object. Setting a name and value pair is as simple as this:

html5_localstorage/javascripts/storage.js
localStorage.setItem("background_color", $("#background_color").val());

Grabbing a value back out is just as easy:


html5_localstorage/javascripts/storage.js
varbgcolor= localStorage.getItem("background_color");

Let’s create a method for saving all the settings from the form. Create the file
javascripts/storage.js and add this code:

html5_localstorage/javascripts/storage.js
var save_settings= function(){
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();
};

This method pulls the values out of the form fields and puts them into the
keys in localStorage.

Next, let’s build a similar method that will load the data from the localStorage
system and place it into the form fields.

report erratum • discuss

Saving Preferences with Web Storage • 187


Download from Wow! eBook <www.wowebook.com>

Free download pdf