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

HTML5 and the clear() Method


In this sixth part of the series, you'll learn how to use the “clear()” method provided by the “localStorage” object to clear in one go all the items saved in the local storage. The underlying logic of this method is extremely simple to follow, so you won’t have major difficulties employing it within your own JavaScript applications.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
January 24, 2011
TABLE OF CONTENTS:
  1. · HTML5 and the clear() Method
  2. · Flushing the local storage with the clear() method

print this article
SEARCH DEVARTICLES

HTML5 and the clear() Method - Flushing the local storage with the clear() method
(Page 2 of 2 )

To be frank, using the "clear()" method to flush the contents of the local storage all at once is an extremely simple process that can be mastered in a snap. Since the best way to demonstrate this is by example, below I wrote an amended version of the previous "HTML5Storage()" function, which now invokes this method after storing some sample items. Take a look at it:

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();
}
 
That was short to code and read, wasn't it? As you can see from the above code fragment, once the function saves some data corresponding to our friend Julie Smith, it calls the "clear()" method, deleting all the contents present in the storage. What's more, in the end the function again pops out an alert box, telling us that the number of existing items is 0. Needless to say, coding a function like this is simply pointless. But in this case you'll have to bear with me, as I did it only for demonstration purposes.

But hold on a second! As you may have noticed, the previous function is called after its containing web page finishes loading. So, it's necessary to create the page in question and include the function in it. Don't worry, though, as this will be done in the following segment.

Now, read the lines to come.

Embedding the previous JavaScript function into a web page

As I said above, below you'll find a sample HTML5 document that attaches the previous "HTML5Storage()" function, in this way implementing an example that shows how to use the "clear()" method in a pretty basic manner. In its current state, the document looks like this: 

<!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>

Mission accomplished, at least for the moment. Now, if you test the above web page on your own browser (assuming that it supports the local storage feature), you should see a sample alert box telling you that there are no items in the local storage. Although somewhat basic, this example permits you to see how the "clear()" method does its business without having to create or define a more complex function, or developing an entire JavaScript application.

From this point onward, you're free to tweak all of the code samples shown in this tutorial. That will surely fire up your own spark of creativity and give you more ideas for how to utilize the previous "clear()" method in a truly useful fashion. 

Final thoughts

In this sixth chapter of the series, you learned how to use the "clear()" method provided by the "localStorage" object, which as you just saw, comes in handy for clearing in one go all of the items saved in the storage. The underlying logic of this method is extremely simple to follow, so you won't have major difficulties employing it within your own JavaScript applications.

It's valid to stress, however, that the pertinent object includes an additional method, called "key()," that can be used for retrieving the keys assigned to the elements saved in the browser. With that said, in the forthcoming tutorial I'll be taking a close look at this method, so you can learn how take advantage of its functionality.

As usual, 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