Out with cookies, in with local storage — jStorage and jQuery

HTML5 Local Storage and jStorage

If you still find yourself on occasion using cookies when developing websites — to remember some setting, or selection, or whatever, stop it! Cookies suck — all you can do is store simple strings, which doesn’t give you a lot of options when you need to store complex information that might require an array or an object.

Local storage, on the other hand, is an HTML5 specification that allows browsers to store objects, XML or JSON data easily and it’s fairly widely supported. Better yet, with the jStorage library it works on pretty much every browser of consequence, including IE7 and IE6, where it falls back to userData behaviour. The only downside in case of IE7 and IE6 is that storage size is limited to 128KB, whereas in most other browsers it’s 5MB.

jStorage

jStorage was written by Andris Reinman and it sets up a straightforward API for interacting with local storage, as well as a fallback to userData in older IE browsers. You can read up and download jStorage at http://www.jstorage.info/. If you use MooTools, Prototype or jQuery in your project then you can just add jStorage to it and start using it. With that being said, it actually only relies on those libraries for JSON encoding and decoding, so if you have your own implementation of that then you don’t even need those frameworks.

It’s dead-easy to use too. Here is the really short of it — get(key), set(key, value), deleteKey(key). At the most basic, that’s all you need and you can see how simple it is. There are a few more useful methods for things like setting expiration date, looking up all existing keys, etc. I won’t list all the methods here, but you can check out the full documentation for details. Instead I’ll use an example of a common functionality to demonstrate jStorage, with the assistance of jQuery.

Using jStorage to remember username

So let’s say you have a fairly standard login form, something like this

<form id="loginForm" name="loginForm" method="POST">
	<label>
		<span>Username:</span>
		<input type="text" id="username" name="username" placeholder="enter username or email" required>
	</label>
	<label>
		<span>Password:</span>
		<input type="password" id="password" name="password" required>
	</label>
	<div class="form-footer">
		<label><input type="checkbox" id="remember" name="remember">Remember username</label>
		<button type="submit" id="loginButton" name="loginButton>Log In</button>
	</div>
</form>

As you can see, the form has a “Remember username” checkbox, so the user can check it off and next time they load the page, their username will be pre-filled. Thanks to jStorage and jQuery implementing this functionality is a snap. The code for it is below and I’ve put the detailed explanations as comments, so check it out.

// start this when DOM is ready
$(function(){
	var checkbox = $('#remember'),
		userField = $('#username'),

		// assign the key name to a variable
		// so we don't have to type it up every time
		key = 'savedUsername',

		// use jStorage to retrieve a stored key
		// on first load this is going to return undefined
		username = $.jStorage.get(key);

	// if a username was saved from previous session
	// set the value of the username field to that
	// tick off the checkbox and set focus on password field
	if (username) {
		userField.val(username);
		checkbox.prop('checked', true);
		$('#password').focus();
	}

	// if username wasn't saved then
	// set username field value to blank and focus on it
	// and make sure the checkbox is unchecked
	else {
		userField.val('').focus();
		checkbox.prop('checked', false);
	}

	// when form is submitted check the checkbox
	// if it's checked then save the username using jStorage
	// if not then delete whatever saved username exists
	$('#loginForm').submit(function(e){
		if (checkbox.prop('checked')) {
			$.jStorage.set(key, userField.val());
		}
		else {
			$.jStorage.deleteKey(key);
		}
	});
});

And that’s it. Now, granted, for something as simple as that you could’ve used cookies as well and it would’ve been just as fine, but the beauty of jStorage is that you can just as easily store much more complex data. For example, here’s how easy it is to save an entire form

$.jStorage.set('savedForm', $('formID').serializeArray());

I’ve discovered jStorage myself only recently, but since I did I never touched a cookie again. Well, “browser cookie”, I touch regular cookies all the time while I eat them.

(3) Comments

  1. zealmurapa
    October 16, 2012

    Good idea, how do check that against a server? I mean suppose you want to sync the login credentials in the cloud.

  2. Himanshu Babbar
    July 10, 2013

    Hi
    While trying to implement jStorage for my web application, i realized that the objects that i need to store are about 3 mb in size. According to the following http://goo.gl/FJxVn i can store only 2.5 Mb. Is there any way i can increase the size or any workaround i can use for this?

    • Ilia
      July 10, 2013

      Based on jStorage site itself most browsers these days do support at least 5MB of storage space (section 4). You can also use this page by Artemy Tregubenko to test the limits of local storage of your browsers (this is of course of limited use since it just tells you the limits for your browsers, your users’ browsers).

      You might also try to split the information and use subdomains to store it in chunks, thought I’m not sure that will work.

      Finally, take another look at the information you need to store — perhaps you can optimize it and reduce the size.

      Beyond that I’m not sure what else can be done.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>