Home arrow HTML arrow 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
(Page 1 of 2 )

If you’re a web designer who thinks that the only enhancements that HTML5 brings to the table are strictly focused on providing new elements that help you to build better and more semantic web pages, you're in for a surprise. The specification includes a shiny new JavaScript object called “localStorage,” which can be used for easily persisting data in the browser.

Of course, if you’ve been a loyal reader of this series and have already read all of the previous installments, then it’s quite probable that you now have a solid background in how to use the object for saving and fetching strings from the local storage. And I’m saying this because in the course of those tutorials, I developed some basic examples that demonstrated how to perform these tasks, along with a few additional ones. These included flushing the entire storage via the “clear()” method and determining the number of items present in it with the “length” attribute.

Although the methods covered so far are functional enough for you to start using the “localStorage” object in the development of more realistic applications (that do more than save/retrieve trivial strings and pop up a few alert boxes), the truth is that I still haven't finished covering the object’s API. It includes an additional method called “key(),” which permits you to retrieve the keys assigned to elements saved in the browser.

If you're interested in learning how to work with this method, in this seventh part of the series, I’m going to build another hands-on example. It will show how to work with the method in a very friendly fashion.

Now, don’t waste more time in preliminaries; begin reading!

Review: clearing the local storage with the “clear()” method

Even though the use of the “clear()” method covered in the previous tutorial is extremely intuitive (its name says it all), before I explain how to get the key of the elements saved in the browser, I’d like to spend a few moments reintroducing the example created in the previous part of the series. It shows in a nutshell how to employ this convenient method.

Check out the code below to see how this concrete example was developed.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 local Storage</title>
<script type="text/javascript">
// using the clear() 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');
    }
    // clear the local storage
    localStorage.clear();
    alert('The number of items saved to the local storage is: ' + localStorage.length);
}
// 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>

The above code is pretty self-explanatory. All that the above “HTML5Storage()” function does is save some items in the local storage, and then delete them via the pertinent “clear()” method. Of course, the best way to prove that this is actually what happens is by checking to see if there are any items still present in the storage after the “wiping” process occurs. This is accomplished via the “length” attribute, which in this case returns a big 0.

Assuming that you already know how to work with the “clear()” method, it’s time to play with another one provided by the “localStorage” object. As noted in the introduction, it’s also possible to retrieve the keys associated with each stored element through a method called “key().” In the upcoming section, I’m going to demonstrate how to use this new method with another approachable example.

Now, jump forward 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