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

As it name suggests, "localStorage" is a powerful JavaScript object that comes with HTML5 (yes, not all of the specification's improvements are exclusively related to the markup). It will let you save up to 5 MB of data in the browser, and best of all, the stored items will remain available until you close the browser's window. Is this the start of a long good-bye to cookies? That may be a bit premature, but only time (and browser vendors) will tell.

To demonstrate how to take advantage of the functionality provided by localStorage, in earlier chapters of this series I developed some examples that showed how to save and retrieve strings from the local storage by using the object's "setItem()" and "getItem()" methods. Thanks to the flat learning curve of this mutator/getter tandem, the storage and retrieval processes were a breeze to achieve.

It's worth stressing, however, that it's also possible to store and fetch data from the object using a syntax that is slightly shorter and tighter than the one offered by the aforementioned methods. This alternate syntax is pretty common in many JavaScript programs. It consists of using an "object[property]" notation. If this is translated to the local storage context, then the storage process would be reduced to writing something like "localStorage['key'] = value, while the opposite task would be achieved by means of an expression similar to value = "localStorage['key']. Do you understand the point of this approach? I guess you do

Anyway, in the following lines I'm going to create a concrete example which will illustrate how to employ this compact syntax when saving and getting data from the local storage. So, are you ready to learn the full details of this brand new example? Then start reading!

Review: using the setItem() and getItem() methods

As I stated in the introduction, the team composed of the "setItem()" and "getItem()" methods makes it really easy to save and retrieve data from the browser's local storage. But if you missed out the previous installment of the series, where I explained how to use these methods within the same JavaScript function, don't fret. Below I included for you the source code corresponding to this example, so you can study it in detail and quickly grasp its underlying logic. Here it is:

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

Although the implementation of the above "HTML5Storage()" function is super simple, it shows how easy it is to store some strings in the local storage through the "setItem()" method and get them back later on via its counterpart, "getItem()." Of course, if you want to see the output that the function produces, then you should test it using your own browser. If all goes as expected, you should be confronted with an alert box that displays some basic information about our fictional user, Julie Smith.

Undeniably, the beauty of this piece of code is that the data will remain available in the local storage even if you close its window's tab (assuming that other tabs have been previously opened). Now, are you starting to realize how useful the local storage can be when used in more realistic use cases? I bet you are!

Before I get to that point, though, it'd be pretty helpful to redefine the earlier "HTML5Storage()" function using the alternate syntax discussed at the beginning. This way, you can pick the notation that best suits you preferences.

That's precisely what I plan to do in the next segment. Thus, jump ahead 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