Home arrow HTML arrow Page 2 - HTML5 Local Storage and the getItem() Method
HTML

HTML5 Local Storage and the getItem() Method


In this third part of a series, you will learn how to get previously saved data from the browser by using the "getItem()" method provided by the "localStorage" object. You'll be amazed at how simple it is to use this method.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 11
January 10, 2011
TABLE OF CONTENTS:
  1. · HTML5 Local Storage and the getItem() Method
  2. · Retrieving data from the local storage with the getItem() method

print this article
SEARCH DEVARTICLES

HTML5 Local Storage and the getItem() Method - Retrieving data from the local storage with the getItem() method
(Page 2 of 2 )

As you may have already guessed, using the "getItem()" method is as easy as working with its cousin "setItem()." The only argument that this brand new method accepts is a literal key, which is used to retrieve data previously stored in the local storage.

It's time to write some functional code that shows how to employ the method.  Below I introduced some minor changes to the previous "HTML5Storage()" function, which this time takes advantage of the functionality of the "getItem()" method to retrieve some sample strings and display them on screen.

Here's how this enhanced version of the function looks:

// add and get some items from the local storage
function HTML5Storage() {
    // add the items to the local storage
    if ('localStorage' in window && window['localStorage'] !== null) {
        localStorage.setItem('fname', 'Julie');
        localStorage.setItem('lname', 'Smith');
        localStorage.setItem('email', 'julie@domain.com');
    }
    // get the items from the local storage
    var fname = localStorage.getItem('fname');
    var lname = localStorage.getItem('lname');
    var email = localStorage.getItem('email');
    alert('First Name: ' + fname + ' Last Name: ' + lname + ' Email: ' + email);
}
// call the 'HTML5Storage()' function when the web page is loaded
window.onload = function() {
    HTML5Storage();
}

Definitely, you'll have to agree with me that the previous function is a bit more useful, thanks to the incorporation of the "getItem()" method. In this case, the function first saves data about a fictional user in the local storage, which is retrieved through the method in question and embedded into an alert box. Naturally, there's not much that can be done with this function, at its implementation is somewhat contrived. However, it's useful for demonstrating how easy it is to save to, and fetch data from, the browser's local storage by using the paired "setItem()/getItem()" methods.

Of course, this function should be attached to an HTML5 document, so you can give it a try and see the result that it produces. That's precisely what I'll be doing below, so keep reading. 

Embedding the previous JavaScript code into an HTML5 document

If you want to see for yourself if the earlier "HTML5Storage()" function really saves the supplied data in the local storage and then gets it back for display purposes, then copy and paste the source code of the following HTML5 document:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 local Storage</title>
<script type="text/javascript">
// add and get some items from the local storage
function HTML5Storage() {
    // add the items to the local storage
    if ('localStorage' in window && window['localStorage'] !== null) {
        localStorage.setItem('fname', 'Julie');
        localStorage.setItem('lname', 'Smith');
        localStorage.setItem('email', 'julie@domain.com');
    }
    // get the items from the local storage
    var fname = localStorage.getItem('fname');
    var lname = localStorage.getItem('lname');
    var email = localStorage.getItem('email');
    alert('First Name: ' + fname + ' Last Name: ' + lname + ' Email: ' + email);
}
// 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>

Armed with this basic example, you should be able to test the functionality of the "localStorage" object. But how? The testing process is quite simple: launch your browser (remember that, aside from Firefox, Safari, and Chrome, local storage is only supported by IE8+), then open a new tab and run the above web page. If all goes well, you should see an alert box displaying the data corresponding to our loyal friend, Julie Smith. But, that's not a big deal, right?

Well, not so fast. Now close the tab associated with the previous web page, and remove from the "HTML5Storage()" function all the lines that that store data in the browser. Done? Good.

Now, reopen the same tab and carefully watch the output that you get. Yes, the alert box displays the same information again! This shows that the data has effectively persisted, even though the browser's tab was closed.

Though simple, this example opens the door to using the "localStorage" object in a few clever ways. But before I get to that point, it's necessary to cover some other useful properties exposed by the object, which deserve a close analysis.  

Final thoughts

In this third installment of the series, you learned how to get previously saved data from the browser by using the "getItem()" method provided by the "localStorage" object. As you just saw, the usage of the method is so simple that it doesn't bear any further discussion.

It's valid to note, though, that it's also possible to perform the storage and retrieval processes by employing a shortened "object[property]" syntax (instead of the longer "setItem()/getItem()" approach). Indeed, this shortened approach is supported by all of the JavaScript objects, including our handy "localStorage." Therefore, in the next tutorial I'll be demonstrating how to work with this tighter syntax, as usual through another hands-on example.

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