Home arrow HTML arrow HTML5 Local Storage and the setItem Method
HTML

HTML5 Local Storage and the setItem Method


In this second part of the series, you will learn how to save some chunks of string data in the browser with the “setItem()” method provided by the “localStorage” object. The entire process is as simple as passing a “key/value” pair to the pertinent method.

Author Info:
By: Alejandro Gervasio
Rating: 4 stars4 stars4 stars4 stars4 stars / 4
January 05, 2011
TABLE OF CONTENTS:
  1. · HTML5 Local Storage and the setItem Method
  2. · Introducing the setItem() method

print this article
SEARCH DEVARTICLES

HTML5 Local Storage and the setItem Method
(Page 1 of 2 )

If you think that the bulk of enhancements and new features incorporated into HTML5 are exclusively related to markup, keep reading for some good news that you weren’t expecting to receive. It’s rather hard to believe, I know, but the specification includes a brand new characteristic called “local storage,” which can be used for storing up to 5 MB of data in the client in a pretty cross-browser fashion. And best of all, the data will remain available until you close your browser’s window. That sounds pretty good, huh?

Briefly, “localStorage” is a JavaScript object that will let you save and fetch data by using either a combination of mutators/getters, or by directly assigning and retrieving values dynamically from its properties. Currently, “localStorage” only supports storing data in the form of strings, but this limitation can be easily overcome by JSON-encoding other data types, like objects and even collections.

Of course, before you start taking advantage of the functionality offered by “localStorage,” you must first check that you’re using a browser that supports it. That’s exactly the topic I discussed in the first part of this series, using a functional code sample to make my point. However, if you’re anything like me, you're eager to see how to use the object for saving data in the browser.

As I just said, this task can be performed easily by means of a setter method provided by the object, called “setItem().” Therefore, in the lines to come I’ll be showing how to utilize this convenient method to store some basic strings in the client.

Are you ready to learn more about the handy “localStorage” HTML5 object? Then begin reading right now!

Review: checking browser support for the “localStorage” object

As always, before I explain how to save some data in the browser by using the “setItem()” method provided by the “localStorage” object, I'll review the example developed in the introductory chapter of this series. It implemented a simple function to check if the object in question was supported by the client.

With that said, here’s the HTML5 document that uses this basic function. Take a look at it:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Testing HTML5 local Storage support</title>
<script type="text/javascript">
// testing HTML5 storage support
function testHTML5Storage() {
    if ('localStorage' in window && window['localStorage'] !== null) {
        alert('HTML5 localStorage is supported by your browser!');
    }
}
// call the 'testHTML5Storage()' function when the web page is loaded
window.onload = function() {
    testHTML5Storage();
}
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #ccc;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
p {
    margin: 0 0 10px 0;
}
#wrapper {
    width: 960px;
    margin: 0 auto;
    background: #fff;
}
#header, #content, #footer {
    padding: 20px;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <header>
            <h1>HTML5 Storage</h1>
            <section>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
            </section>
        </header>
    </div>
    <div id="content">
        <h2>This is the main content section</h2>
        <section>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </section>
        <section>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </section>
    </div>
    <div id="footer">
        <footer>
            <h2>This is the footer</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p> 
        </footer>
    </div>
</div>
</body>
</html>

Since “localStorage” is a property of the “window” JavaScript object, the above “testHTML5Storage()” function simply checks to see if the property exists, and if it is not null. If the result of this process is true, an alert box is displayed on screen with a trivial message. Logically, it’s possible to use some DOM methods to embed the message directly into the containing document; since the function is so simple, however, I don’t think it's really worth the hassle in this case. 

So far, so good. Now that you've already grasped the underlying logic of the earlier function, it’s time to do something more useful and fun with the “localStorage” object. So in the next section I'll be developing another approachable example. It will use the object’s “setItem()” method to save some trivial strings in the browser.

To learn the full details of this brand new example, click on the link below and keep reading.  


blog comments powered by Disqus
HTML ARTICLES

- Does HTML5 Need a Main Element?
- Revisiting the HTML5 vs. Native Debate
- HTML5: Not for Phone Apps?
- HTML5 or Native?
- Job Hunting? Freelancer.com Lists This Quart...
- HTML5 in the News
- Report: HTML5 Mobile Performance Lags
- The Top HTML5 Audio Players
- Top HTML5 Video Tutorials
- HTML5: Reasons to Learn and Use It
- More of the Top Tutorials for HTML5 Forms
- MobileAppWizard Releases HTML5 App Builder
- HTML5 Boilerplate: Working with jQuery and M...
- HTML5 Boilerplate Introduction
- New API Platform for HTML5

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials