HTML5 localStorage: Tutorial and Basics

HTML5 is a new hot technology that adds a new feature to modern browsers which allows them to store a certain amount of website data locally on someone's computer. This hot solution comes in handy with some of the recent "web apps" that might, for example, save your drafts or states even when disconnecting from the Internet, such as Microsoft Office online apps but may allow you to work offline, GMail offline, etc.

In fact, this solution is a JavaScript API known as localStorage, and in this HTML5 tutorial, we'll be covering some of the HTML5 localStorage basics and how it works.

Some other HTML5 related tutorials you should read:
- HTML5 Web Workers Multithreading in JavaScript
- Design Better HTML5 Form Element Validator
- JavaScript Image Rotation script with CANVAS in HTML5
- Processing Local Files in JavaScript with HTML5
- JavaScript Caching in HTML5
- Awesome Canvas Drawer with HTML5

Sampled by ©



Let's clear up some of the ideas around localStorage. You might be aware of "cookies", which sites use to remember you or your login. Cookies are very limited in size, and really aren't meant to store actual data. localStorage, on the other hand, is meant for sites to have a 5-10MB space on your PC to save whatever they may need. This storage is NOT sent to the server, in contrast to cookies. This means all data stored with localStorage is kept on that one computer, and only accessible by the browser you used to create the data. Every modern browser supports this, so let's look into the code (Javascript knowledge is needed):

You can access localStorage with window.localStorage. If you type that into a console, you'll probably see that the current site you call it from isn't using it.

Firebug console

The way localStorage actually stores its data is with string key/value pairs. You either set or get the values by their key string. For example, I might add a key named "user", and set its value to "John": window.localStorage.setItem('user','John'). Now if you call window.localStorage you'll see you have 1 item.

setItem with localStorage

Now that you've set an item, you can also get it's value by calling it by its string: window.localStorage.getItem('user')

getItem with localStorage

One more method to add to these localStorage basics would be window.localStorage.clear(), which as you might guess, clears out everything in localStorage.

Clear localStorage

Simple Site

So far everything seems pretty simple, right? Let's see a simple, real world example of how we can use this. Let's make a small notepad type app, that will store everything we type into it, into our localStorage. Let's set up some quick markup first:

<html lang="en-US">
<meta charset="UTF-8">
<title>localStorage Notepad</title>

<style type="text/css">
body {
background: #ABC;
font-family: Helvetica, Arial, sans-serif;

.notepad {
background: #FAFAFA;
border: 1px solid #CCC;
border-radius: 5px;
box-shadow: 1px 1px 3px rgba(0,0,0,0.4);
min-height: 400px;
margin: 0 auto;
padding: 20px;
width: 440px;
<div class="notepad" contentEditable="true"></div>

<script src=" "></script>
$( function() {
//Stuff to come

Which would give us a page like so:

Notepad page

You might notice at the end I decided to use Zepto.js from a CDN, basically I'm just using it to slim down on the Javascript we have to write. Anyway, you'll notice that at the moment all we have is a div that you can type into, but that's about it. Once you refresh the page, the notepad is blank once again. Let's plug in some localStorage magic!

Store it!

$( function() {
// Set some variables
var ls = window.localStorage

// Save text
$('.notepad').blur( function() {
ls.setItem('data', $('.notepad').text() );

You'll see we've added some extra stuff to our Javascript. Zepto acts just like jQuery for the most part, so upon initialization we first set an alias to window.localStorage, that way we can just use ls instead of window.localStorage typing out over and over. The next thing we do is a bind a function to the blur event (i.e. when you remove focus) of the .notepad div. In this case, we want the page to save the text that it contains whenever we remove focus from the pad. Now you can call window.localStorage after you type new text and see that it's being saved locally!

Notepad setItem to text

Read it too

Great, we've added saving to our notepad app, but if you refresh the notepad is still blank like before. However, if you call window.localStorage in a console, you will see that the saved text still exists. All we need to do is add a little more JS to retrieve any saved data and apply it on load!

$( function() {
// Set some variables
var ls = window.localStorage

// Check for local data, then apply
if (ls.getItem('data')) {

// Save text
$('.notepad').blur( function() {
ls.setItem('data', $('.notepad').text() );

With that middle section, you'll see we first check for the existence of any saved text (excluding line breaks) under the "data" key, and if so, apply it to the notepad div. With that, you now have a super simple notepad app using some localStorage basics!

Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB
WordPress Landing Page Conversion Essentials to Convert More
4 Development Hacks To Make Your Website Launch A Success
Why Data Recovery Software and Services are Important
Why Engineers Specializing in DevOps Are the Wave of the Future
The Ultimate Checklist for HTTP to HTTPS Migration

Top view articles
65 Free JavaScript Photo Gallery Solutions
Top 10 Beautiful Christmas Countdown Timers
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
Top 10 Free Web Chat box Plug-ins and Add-ons
50+ Beautiful Resources of HTML Form using CSS and JavaScript
Top 10 Best JavaScript eBooks that Beginners should Learn
The Ultimate JavaScript Tutorial in Web Design
HTML5 Web Workers Multithreading in JavaScript
Learn more about JavaScript Inheritance with Tiny JavaScript Example Codes

Free JavaScript Tutorials & Articles