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 © JavaScriptBank.com

---

The API

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:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<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;
}
</style>
</head>
<body>
<div class="notepad" contentEditable="true"></div>

<script src="http://cdnjs.cloudflare.com/ajax/libs/zepto/1.0rc1/zepto.min.js "></script>
<script>
$( function() {
//Stuff to come
});
</script>
</body>
</html>

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!

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

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

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!

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

// Check for local data, then apply
if (ls.getItem('data')) {
$('.notepad').text(ls.getItem('data'));
}

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

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!

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

Recent articles
Insights for Advanced Zooming and Panning in JavaScript Charts
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
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


Top view articles
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
Top 10 Beautiful Christmas Countdown Timers
Top 10 Best JavaScript eBooks that Beginners should Learn
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com