Home arrow HTML arrow Page 2 - HTML5 and the key() Method
HTML

HTML5 and the key() Method


In this seventh tutorial of the series, I introduce the “key()” method provided by the “localStorage” object. This method allows you to easily retrieve the keys assigned to items saved in the browser. While its relevance is certainly minor, especially when compared with the workhorses “setItem(),” getItem()” and “removeItem(),” the “key()” method has its place, as you'll soon see.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 1
January 25, 2011
TABLE OF CONTENTS:
  1. · HTML5 and the key() Method
  2. · Introducing the key() method

print this article
SEARCH DEVARTICLES

HTML5 and the key() Method - Introducing the key() method
(Page 2 of 2 )

  

There may be times when it’s necessary to retrieve the key used to save a specific element (or elements) in the local storage. In a case like this, the retrieval process is simple, thanks to the existence of the “key()” method mentioned in the previous segment.

To illustrate the usage of this new method more clearly, below I rewrote the earlier “HTML5Storage()” function, whose implementation now looks like this:  

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');
    for(var i = 0; i <= localStorage.length-1; i++) {
        alert(localStorage.key(i));
    }
}
// call the 'HTML5Storage()' function when the web page is loaded
window.onload = function() {
    HTML5Storage();
}

As you can see from the code above, the function first saves some items in the storage, which are fetched back via the already familiar “getItem()” method. Admittedly, this process offers nothing especially interesting, with a subtle exception: at the end the function iterates over the pertinent items and echoes their keys to the browser through the “key()” method.

According to the rationale of the function, it should display the values “fname,” “lname” and “email,” right? To find out if it actually does this, we'll attach the function to a sample HTML5 document and see what happens.

Keep reading; the answer to this burning mystery can be found below.  

Seeing the function in action: adding markup

If you want to see if the previous function does what it seems to do, here’s a basic HTML5 page that calls it after the entire DOM has been loaded. Take a peek at it:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 local Storage</title>
<script type="text/javascript">
// using the key() method
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');
    for(var i = 0; i <= localStorage.length-1; i++) {
        alert(localStorage.key(i));
    }
}
// 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>

There you have it. At this point, if you test the above HTML5 document by using a browser that offers support for the “localStorage” object, you should see a sequence of three alert boxes displaying the keys of the elements previously stored. Of course, this isn’t the most useful way to work with the “key()” method, but it does show its functionality.

Feel free to tweak all of the code samples included in this tutorial, a process that will help you to develop a better understanding of how to fetch and manipulate the keys assigned to the elements saved in the local storage. 

Final thoughts

In this seventh tutorial of the series, I took a quick look at the “key()” method provided by the “localStorage” object, which allows you to easily retrieve the keys assigned to items saved in the browser. While its relevance is certainly minor, especially when compared with the workhorses “setItem(),” getItem()” and “removeItem(),” the “key()” method has its place, so if you ever need to use it, hopefully the example created before will assist you in the process.

At this point, I've covered the entire API exposed by local storage, meaning that it’s time to start employing it in more realistic use cases. With that idea in mind, in the forthcoming installment I’ll be illustrating how to create a highly customizable client-side visitor counter by using something as simple as a single JavaScript function.

Want to see how this will be achieved? Then 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