Home arrow HTML arrow Page 2 - Storing and Getting Items Using Shorter Notation in HTML5
HTML

Storing and Getting Items Using Shorter Notation in HTML5


In this fourth part of a series, I'll expand your knowledge of the “localStorage” object by showing you how to save and fetch data from the browser with a slightly tighter syntax. Whether you utilize the “setItem()/getItem()” methods or the “object[property]” notation we'll discuss here, you’ll get exactly the same results.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
January 11, 2011
TABLE OF CONTENTS:
  1. · Storing and Getting Items Using Shorter Notation in HTML5
  2. · Using an abbreviated syntax to save and get items from the local storage

print this article
SEARCH DEVARTICLES

Storing and Getting Items Using Shorter Notation in HTML5 - Using an abbreviated syntax to save and get items from the local storage
(Page 2 of 2 )

To be frank, saving to and fetching data from the "localStorage" object using the "object[property]" notation mentioned in the previous segment is identical to working with any other JavaScript object, be it native or user-defined. To expand on this concept, however, in this case I'm going to redefine the already familiar "HTML5Storage()" function. It will use this abbreviated notation and whose implementation will look like this:

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

As you can see from the above code snippet, the function does exactly the same thing as in its initial definition, except that it now uses a shorter syntax to store and recover the sample data from the local storage. Moreover, if you're used to manipulating the properties of your JavaScript objects by utilizing the square bracket notation "[]", the modified implementation of the "HTML5Storage()" function should be pretty easy to follow. Of course, you can always switch over to the intuitive "setItem()" and "getItem()" methods, so feel free to do so if you feel more comfortable with them.

Despite the rather subtle changes just introduced, the function should be included in an HTML5 document so that it can work properly, right? Well, that's exactly what I'll be doing below, so read the next few lines.

Adding the previous JavaScript function to an HTML5 page

If you're anything like me and want to see if the shortened version of the previous "HTML5Storage()" function works properly, below I attached the pertinent function to a basic HTML5 document, so you can test it and tweak it at will. Take a look at the following code sample:

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

That's not rocket science, is it? If you give the above web page a try using a browser that supports the "localStorage" object, you should see an alert box displaying the stored data about our hypothetical user, Julie Smith. In simple terms, this means that even though the items were saved and fetched using a different notation, the object remained entirely functional.

And with this final example, we've come to the end of this tutorial. As usual, feel free to tweak all of the code samples developed before to get some good practice in using the local storage feature within your own HTML5 documents.

Final thoughts

In this fourth episode of the series, you expanded your existing background in the "localStorage" object by learning how to save and fetch data from the browser using a slightly tighter syntax. Whether you utilize the "setItem()/getItem()" methods or the "object[property]" notation just discussed, you'll get exactly the same results. So, which approach to pick is a matter of personal preference.

So far, I've demonstrated how to store and retrieve items. But what if you need to explicitly delete a specific item? Does the "localStorage" object feature that functionality? Well, fortunately the object provides another method, called "removeItem()," which performs exactly that task. And in the next tutorial, I'm going to set up another example that will show how to work with it.

Here's my little piece of advice: 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