Hans Sprecher

Take it Off[line]

Hans Sprecher, @honzie

26.7.2011

One of my friends really doesn't like this site. He has two problems with it:

I couldn't diagree more—but this is why it's my site and not his.

Customize this site!

Add some hex codes



e.g. #234

Note: The above turn into color pickers in Opera 11. Cool.

Reset

HTML5 Offline Storage

It got me to thinking though. Can I easily create a page on my site that will allow my friend (or any other visitors) to change the colors on my site?

Now, I don't want to store everyone's preferences on my own server. That would involve setting up a database, and storing their information, and probably setting cookies.

Yick.

HTML5 to the rescue! Just change whatever settings you like down below, click save, and watch your new preferences follow you around the site. Of course, this only works if your browser supports offline storage.

The Inner Workings

There are two input tags. Each has 'pickme' as its class. This allows us to select it using JQuery when it changes (either blur, or when the 'enter' key is pressed on the keyboard).

set_css = function() {
	$('body').css('background-color',
	  localStorage.getItem('background-color'));
	$('body').css('color',localStorage.getItem('color'));
};
if (Modernizr.localstorage) {
	$('.pickme').change(function() {
		localStorage.setItem(this.id,this.value);
		set_css();
	});
	set_css();
}
			

The magic is passing strings as keys and values to localStorage. From localStorage, you can either getItem or setItem. Of course, set_css() could be made a bit DRYer, iterating through an array to set the values.

The set_css() function is defined and called on document.ready on each interior page, allowing the color choices to follow you around.

Thoughts? Hit me up on Twitter @honzie.