Home arrow HTML arrow Optimizing Web Form Autosavers in HTML5
HTML

Optimizing Web Form Autosavers in HTML5


If you’re a web designer who wants to learn how to take advantage of the powerful local storage mechanism provided by HTML5, you’ve come to the right place. Welcome to the final chapter of this article series. Made up of ten tutorials, this series explores the methods and properties included with the “localStorage” HTML5 object, and shows you how to use this object in the development of a few real-word web applications.

Author Info:
By: Alejandro Gervasio
Rating: 4 stars4 stars4 stars4 stars4 stars / 4
February 01, 2011
TABLE OF CONTENTS:
  1. · Optimizing Web Form Autosavers in HTML5
  2. · Optimizing the autosaver's performance

print this article
SEARCH DEVARTICLES

Optimizing Web Form Autosavers in HTML5
(Page 1 of 2 )

And speaking of building web programs that can be utilized in more realistic environments, I left off the last installment demonstrating how to enhance the behavior of a sample contact form. We enabled it to save the data entered into it to the local storage. In this way, we implemented a simple – yet functional -- autosaving feature, similar to the one that can be found in several desktop applications.

To be frank, the results that this web form autosaver currently yields are more than satisfactory, especially since most of its underlying logic was implemented through a couple of JavaScript functions. As with any other program. however, there’s plenty of room to extend the autosaver’s current functionality and even optimize its performance. While the first option will be left as homework for you (yes, feel free to call me lazy if you want to), the second one is slightly more appealing to me. But how can this be done?

Well, it’s possible to minify and compress the JavaScript file that makes the autosaver work properly by using Google’s closure compiler (http://closure-compiler.appspot.com/home), which is also utilized by some of the big players in the field of JavaScript frameworks, including the always venerable jQuery. Therefore, in this last tutorial of the series, I’m going to “squeeze” the aforementioned file, thus finishing this hopefully educational series on the HTML5 local storage.

Ready to see how this optimization will be accomplished? Then let’s get going!

Recap: the previous web form autosaver

In case you still haven’t read the previous chapter of the series, where I explained how to build the web form autosaver mentioned in the introduction, below I included the source files corresponding to this sample application.

First, here is the HTML5 document that displays a basic contact form. Its definition is as follows:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Autosaving a web form with HTML5 local Storage</title>
<script src="autosaver.js"></script>
<link rel="stylesheet" type="text/css" href="default.css" />
</head>
<body>
<div id="wrapper">
    <header>
        <h1>Contact us now!</h1>
    </header>   
    <nav>
        <ul>
            <li><a href="#">About Us</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Products</a></li>
            <li><a href="#">Blog</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>
    <section>
        <form action="processform.php" method="post">
            <fieldset>
                <ol>
                    <li>
                        <label for="subject">Subject: <em>[required]</em></label>
                        <input type="text" name="subject" id="subject" class="text" />
                    </li>
                    <li>
                        <label for="email">Email: <em>[required]</em></label>
                        <input type="email" name="email" id="email" class="text" />
                    </li>
                    <li>
                        <label for="comments">Comments:</label>
                        <textarea rows="10" cols="20" name="comments"></textarea>
                    </li>
                    <li>
                        <input type="submit" name="send" value="Submit" />
                    </li>
                </ol>
            </fieldset>
        </form>
    </section>
    <footer>
        <h2>Footer section</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>
</body>
</html>

The structure of the above web page is extremely basic, as it only includes the corresponding sample contact form, along with a few additional sections, such as the already classic “header” and “footer.” Of course, it’s necessary to give this page a slightly more pleasant look, so below is the definition of a CSS file that does exactly that:  

(default.css)

/* layout styles */
body {
    padding: 0;
    margin: 0;
    background: #0C2478;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
#wrapper {
    width: 960px;
    margin: 0 auto;
    background: #fff;
}
header {
    display: block;
    padding: 20px;
}
nav {
    display: block;
    width: 920px;
    height: 30px;
    margin: 0 auto;
    padding-top: 10px;
    background: #eee;
}
nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
}
nav ul li {
    float: left;
    width: 120px;
    text-align: center;
}
nav ul li a {
    display: block;
    width: 120px;
    text-decoration: none;
    color: #000;
    border-right: 1px solid #ccc;
}
section {
    display: block;
    padding: 20px;
}
footer {
    display: block;
    padding: 20px;
}
/* form styles */
form {
    width: 280px;
    padding: 30px;
    background: #dfefff;
}
form fieldset {
    border: none;
}
form fieldset ol {
    list-style: none;
    padding: 0;
    margin: 0;
}
form fieldset ol li {
    margin-bottom: 10px;
}
form fieldset ol label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}
form fieldset ol label em {
    font-style: normal;
    font-weight: normal;
    color: #00f;
}
form fieldset ol input.text {
    width: 250px;
}
form fieldset ol textarea {
    width: 250px;
}
/* time container */
#time_container {
    color: #00f;
}

In short, this file simply defines some basic styles for building the layout of the earlier web page and for giving the contact form a more engaging appearance. The result of this styling process can be seen more clearly in the following screen shot:

Although I have to admit that this isn't the most attractive form that you’ll ever see in your life, in its current state it’s entirely functional. However, its default behavior can be enhanced by enabling it to autosave the data entered in it. This is precisely the task that the following JavaScript file performs:

(autosaver.js)

// get the state of the form
function getFormState() {
    var fields = document.getElementsByTagName('form')[0].elements;
    if (fields.length == 0){return};
    for (var i = 1; i <= fields.length-1; i++) {
        var name = fields[i].getAttribute('name');
        if (name in localStorage && localStorage[name] !== null) {
            fields[i].value = localStorage[name];
        }
    }
}

// save the state of the form
function saveFormState() {
    var fields = document.getElementsByTagName('form')[0].elements;
    if (fields.length == 0){return};
    var populated = false;
    for (var i = 1; i <= fields.length-1; i++) {
        var name = fields[i].getAttribute('name');
        if (fields[i].value != '' && fields[i].getAttribute('type') != 'submit') {
           localStorage[name] = fields[i].value;
           populated = true;
        }
    }
    // display the time form data was saved (optional)
    if (populated) {
        var date = new Date();
        var hours = date.getHours();
        var mins = date.getMinutes();
        var secs = date.getSeconds();
        hours = (hours < 10) ? '0' + hours : hours;
        mins = (mins < 10) ? '0' + mins : mins;
        secs = (secs < 10) ? '0' + secs : secs;
        var msg = '[Form data was saved at ' + hours + ':' + mins + ':' + secs + ']';
        var timecont = document.getElementById('time_container');
        if (timecont !== null) {
            timecont.innerHTML = msg;
        }
        else {
            timecont = document.createElement('span');
            timecont.setAttribute('id', 'time_container');
            timecont.appendChild(document.createTextNode(msg));
            document.getElementsByTagName('fieldset')[0].appendChild(timecont);
        }
    }
}

// run the above functions when the web page is loaded
window.onload = function () {
    // check if HTML5 localStorage is supported by the browser
    if ('localStorage' in window && window['localStorage'] !== null) {
        // get the form state
        getFormState();
        // save the state of the form each 15 seconds (customizable)
        setInterval('saveFormState()', 15 * 1000);
    }
}

Since the logic driving the above “getFormState()” and “saveFormState()” JavaScript functions was discussed in depth in the preceding installment of the series, I’m not going to waste your time explaining  how they work once again. All that you need to recall is that they use the functionality of the local storage to save and retrieve the data entered into the pertinent contact form, even if its browser tab is closed.

What’s more, the image below depicts quite clearly how this autosaving process takes place. Check it out: 
 

There you have it. Due to the capability that the local storage provides out of the box, the implementation of a customizable web form autosaver was indeed a breeze to achieve. From this point on, you may want to take two different approaches: the first one is to play around with the autosaver and tweak it to suit more specific requirements, while the second one is a bit more pragmatic and consists of minifying its source file.

You already picked the latter? Well, if you wish to learn the full details of this optimization process, jump forward and read the following section.


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