HTML5 and CSS3, Second Edition

(singke) #1
html5_localstorage/javascripts/storage.js
var load_settings= function(){
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, so we’ll use jQuery to modify the element’s styles.

html5_localstorage/javascripts/storage.js
var apply_preferences_to_page= function(){
$("body").css("backgroundColor",$("#background_color").val());
$("body").css("color",$("#text_color").val());
$("body").css("fontSize",$("#text_size").val()+ "px");
};

Finally, we kick all this off at the bottom of the script.


html5_localstorage/javascripts/storage.js
load_settings();

$('form#preferences').submit(function(event){
event.preventDefault();
save_settings();
});

The only thing we have left to do is load our script and jQuery when the HTML
page loads. Add these two lines right above the closing <body> tag:

html5_localstorage/index.html
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<scriptsrc="javascripts/storage.js"></script>

And now the settings persist between browser sessions.


Chapter 9. Saving Data on the Client • 188


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf