Home arrow HTML arrow Page 2 - 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 - Introducing the setItem() method
(Page 2 of 2 )

As I stated previously, you can take a couple of different approaches to saving data through the “localStorage” object. The first one consists of using its “setItem()“ method, while the second one is a little more pragmatic, as it directly uses the “object[property]” notation. For the moment, though, I’m going to explore the former, which you’ll find extremely easy to grasp.

To demonstrate how to employ the “setItem()” method and save some basic strings to local storage, I only need to define a new function similar to the earlier “testHTML5Storage(),” whose implementation will be as follows:

// add some items to the local storage
function HTML5Storage() {
    if ('localStorage' in window && window['localStorage'] !== null) {
        localStorage.setItem('fname', 'Julie');
        localStorage.setItem('lname', 'Smith');
        localStorage.setItem('email', 'julie@domain.com');
    }
}
// call the 'HTML5Storage()' function when the web page is loaded
window.onload = function() {
    HTML5Storage();
}

If I had to say something about the above function, I’d say that it’s really trivial. However, it's useful for showing how to use the “setItem()” method to save some data in the browser. As you can see from the earlier sample code, the method accepts two input arguments. The first one is the key corresponding to the element being stored, while the last one is the element itself.

As I noted previously, “setItem()” (and therefore the “localStorage” object) can only store strings, so if you need to save objects or collections, I’d recommend that you first convert them to JSON to avoid any conflict.

Also, you may have noticed that the previous function is called once the containing web page finishes loading. While this is actually optional, I want to do things the right way and include the function in the same HTML5 document that you saw before.

That's precisely what I plan to do in the coming segment.  

Attaching the earlier function to an HTML5 document

If want to try the function defined above, you can do that simply by copying and pasting the code of the HTML5 document below. Here it is:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 local Storage</title>
<script type="text/javascript">
// add some items to the local storage
function HTML5Storage() {
    if ('localStorage' in window && window['localStorage'] !== null) {
        localStorage.setItem('fname', 'Julie');
        localStorage.setItem('lname', 'Smith');
        localStorage.setItem('email', 'julie@domain.com');
    }
}
// call the 'HTML5Storage()' function when the web page is loaded
window.onload = function() {
    HTML5Storage();
}
</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>

Done. Now, if you test the function by using any browser that supports local storage, the data saved via the pertinent “setItem()” method will remain available, even if you close the browser’s tab. This, in theory, should give you a clearer idea of how to use the object in a truly useful manner.

What's that? You don't have a clue yet? Well, don’t worry; in forthcoming parts of this series I’ll be developing some functional examples. But keep in mind that this is a work in progress.

Closing thoughts

In this second part of the series, things become a little more interesting, as you learned how to save some chunks of string data in the browser through the “setItem()” method provided by the “localStorage” object. As you just saw, the whole process was as simple as passing to the pertinent method a “key/value” pair and nothing else.

While storing data in the browser is all well and good, the procedure would be useless if the data couldn't be fetched for further manipulation. The good news is that the retrieval process is dead simple, thanks to another complementary method included with “localStorage.” Not surprisingly, it's called “getItem().” In the next tutorial I’m going to explore this method in depth, so you can learn how to use it in conjunction with its counterpart “setItem().”

Here’s my final recommendation: don’t miss the next part!  


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

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-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials