Threadbare Canvas Productions

Online Journal of James Hogan the Web Developer
October 21, 2010

Simple Introduction to HTML5 Local Storage API

Okay, so if you not looking into HTML5 your letting the biggest movement in web application development since the introduction of CSS pass you by. In this simple example you can see how an object can be stored into your HTML5 compatible browsers localStorage.

Try this, copy and paste the following code to a simple HTML file and save it onto you desktop. Open it in Chrome or Firefox 4 or Opera. Then, edit the Hello World text. The HTML5 contentEditable=”true” allows the containing element to be editable. This is a really nice attribute that makes textarea redundant in an AJAX app, in my opinion.

After you’ve edited the content close the browser and open the file again. Boom! the change has been stored in the browsers localStorage and is accessible even after a browser shutdown. Pretty sweet right?

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
 <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script>
$(function(){
 var edit = document.getElementById('hello');

 $(edit).blur(function(){
 localStorage.setItem('save', this.innerHTML);
 });

 if(localStorage.getItem('save')){
 edit.innerHTML = localStorage.getItem('save');
 }

});
</script>
<style>
 article, aside, figure, footer, header, hgroup,
 menu, nav, section { display: block; }
</style>
</head>
<body>
 <p id="hello" contentEditable="true">Hello World</p>
</body>
</html>
 

1 Comment to “Simple Introduction to HTML5 Local Storage API”

Leave a Comment