- •Contents at a Glance
- •Contents
- •Foreword
- •About the Authors
- •About the Technical Reviewer
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •An Overview of This Book
- •Example Code and Companion Web Site
- •Contacting the Authors
- •Overview of HTML5
- •The Story So Far—The History of HTML5
- •The Myth of 2022 and Why It Doesn’t Matter
- •Who Is Developing HTML5?
- •A New Vision
- •Compatibility and Paving the Cow Paths
- •Utility and the Priority of Constituencies
- •Interoperability Simplification
- •Universal Access
- •A Plugin–Free Paradigm
- •What’s In and What’s Out?
- •What’s New in HTML5?
- •New DOCTYPE and Character Set
- •New and Deprecated Elements
- •Semantic Markup
- •Simplifying Selection Using the Selectors API
- •JavaScript Logging and Debugging
- •window.JSON
- •DOM Level 3
- •Monkeys, Squirrelfish, and Other Speedy Oddities
- •Summary
- •Using the Canvas API
- •Overview of HTML5 Canvas
- •History
- •What Is a Canvas?
- •Canvas Coordinates
- •When Not to Use Canvas
- •Fallback Content
- •CSS and Canvas
- •Browser Support for HTML5 Canvas
- •Using the HTML5 Canvas APIs
- •Checking for Browser Support
- •Adding a Canvas to a Page
- •Applying Transformations to Drawings
- •Working with Paths
- •Working with Stroke Styles
- •Working with Fill Styles
- •Filling Rectangular Content
- •Drawing Curves
- •Inserting Images into a Canvas
- •Using Gradients
- •Using Background Patterns
- •Scaling Canvas Objects
- •Using Canvas Transforms
- •Using Canvas Text
- •Applying Shadows
- •Working with Pixel Data
- •Implementing Canvas Security
- •Building an Application with HTML5 Canvas
- •Practical Extra: Full Page Glass Pane
- •Practical Extra: Timing Your Canvas Animation
- •Summary
- •Working with Scalable Vector Graphics
- •Overview of SVG
- •History
- •Understanding SVG
- •Scalable Graphics
- •Creating 2D Graphics with SVG
- •Adding SVG to a Page
- •Simple Shapes
- •Transforming SVG Elements
- •Reusing Content
- •Patterns and Gradients
- •SVG Paths
- •Using SVG Text
- •Putting the Scene Together
- •Building an Interactive Application with SVG
- •Adding Trees
- •Adding the updateTrees Function
- •Adding the removeTree Function
- •Adding the CSS Styles
- •The Final Code
- •Summary
- •Working with Audio and Video
- •Overview of Audio and Video
- •Video Containers
- •Audio and Video Codecs
- •Audio and Video Restrictions
- •Browser Support for Audio and Video
- •Using the Audio and Video API
- •Checking for Browser Support
- •Accessibility
- •Understanding Media Elements
- •Working with Audio
- •Working with Video
- •Practical Extras
- •Summary
- •Using the Geolocation API
- •About Location Information
- •Latitude and Longitude Coordinates
- •Where Does Location Information Come From?
- •IP Address Geolocation Data
- •GPS Geolocation Data
- •Wi-Fi Geolocation Data
- •Cell Phone Geolocation Data
- •User–Defined Geolocation Data
- •Browser Support for Geolocation
- •Privacy
- •Triggering the Privacy Protection Mechanism
- •Dealing with Location Information
- •Using the Geolocation API
- •Checking for Browser Support
- •Position Requests
- •Building an Application with Geolocation
- •Writing the HTML Display
- •Processing the Geolocation Data
- •The Final Code
- •Practical Extras
- •What’s My Status?
- •Show Me on a Google Map
- •Summary
- •Using the Communication APIs
- •Cross Document Messaging
- •Understanding Origin Security
- •Browser Support for Cross Document Messaging
- •Using the postMessage API
- •Building an Application Using the postMessage API
- •XMLHttpRequest Level 2
- •Cross-Origin XMLHttpRequest
- •Progress Events
- •Browser Support for HTML5 XMLHttpRequest Level 2
- •Using the XMLHttpRequest API
- •Building an Application Using XMLHttpRequest
- •Practical Extras
- •Structured Data
- •Framebusting
- •Summary
- •Using the WebSocket API
- •Overview of WebSocket
- •Real-Time and HTTP
- •Understanding WebSocket
- •Writing a Simple Echo WebSocket Server
- •Using the WebSocket API
- •Checking for Browser Support
- •Basic API Usage
- •Building a WebSocket Application
- •Coding the HTML File
- •Adding the WebSocket Code
- •Adding the Geolocation Code
- •Putting It All Together
- •The Final Code
- •Summary
- •Using the Forms API
- •Overview of HTML5 Forms
- •HTML Forms Versus XForms
- •Functional Forms
- •Browser Support for HTML5 Forms
- •An Input Catalog
- •Using the HTML5 Forms APIs
- •New Form Attributes and Functions
- •Checking Forms with Validation
- •Validation Feedback
- •Building an Application with HTML5 Forms
- •Practical Extras
- •Summary
- •Working with Drag-and-Drop
- •Web Drag-and-Drop: The Story So Far
- •Overview of HTML5 Drag-and-Drop
- •The Big Picture
- •Events to Remember
- •Drag Participation
- •Transfer and Control
- •Building an Application with Drag-and-Drop
- •Getting Into the dropzone
- •Handling Drag-and-Drop for Files
- •Practical Extras
- •Customizing the Drag Display
- •Summary
- •Using the Web Workers API
- •Browser Support for Web Workers
- •Using the Web Workers API
- •Checking for Browser Support
- •Creating Web Workers
- •Loading and Executing Additional JavaScript
- •Communicating with Web Workers
- •Coding the Main Page
- •Handling Errors
- •Stopping Web Workers
- •Using Web Workers within Web Workers
- •Using Timers
- •Example Code
- •Building an Application with Web Workers
- •Coding the blur.js Helper Script
- •Coding the blur.html Application Page
- •Coding the blurWorker.js Web Worker Script
- •Communicating with the Web Workers
- •The Application in Action
- •Example Code
- •Summary
- •Using the Storage APIs
- •Overview of Web Storage
- •Browser Support for Web Storage
- •Using the Web Storage API
- •Checking for Browser Support
- •Setting and Retrieving Values
- •Plugging Data Leaks
- •Local Versus Session Storage
- •Other Web Storage API Attributes and Functions
- •Communicating Web Storage Updates
- •Exploring Web Storage
- •Building an Application with Web Storage
- •The Future of Browser Database Storage
- •The Web SQL Database
- •The Indexed Database API
- •Practical Extras
- •JSON Object Storage
- •A Window into Sharing
- •Summary
- •Overview of HTML5 Offline Web Applications
- •Browser Support for HTML5 Offline Web Applications
- •Using the HTML5 Application Cache API
- •Checking for Browser Support
- •Creating a Simple Offline Application
- •Going Offline
- •Manifest Files
- •The ApplicationCache API
- •Application Cache in Action
- •Building an Application with HTML5 Offline Web Applications
- •Creating a Manifest File for the Application Resources
- •Creating the HTML Structure and CSS for the UI
- •Creating the Offline JavaScript
- •Check for ApplicationCache Support
- •Adding the Update Button Handler
- •Add Geolocation Tracking Code
- •Adding Storage Code
- •Adding Offline Event Handling
- •Summary
- •The Future of HTML5
- •Browser Support for HTML5
- •HTML Evolves
- •WebGL
- •Devices
- •Audio Data API
- •Touchscreen Device Events
- •Peer-to-Peer Networking
- •Ultimate Direction
- •Summary
- •Index
CHAPTER 8 USING THE FORMS API
Using the HTML5 Forms APIs
Now that we’ve spent some time familiarizing ourselves with the new form element types, let’s turn to the attributes and APIs that are present on both the old and new form controls. Many of them are designed to reduce the amount of scripting needed to create a powerful web application user interface. You may find that the new attributes give you the power to enhance your user interface in ways that you had not considered. Or, at the very least, you may be able to remove blocks of script in your existing pages.
New Form Attributes and Functions
First, we’ll consider new attributes, functions, and a few elements that did not previously exist in earlier versions of HTML. Like the new input types, it is generally safe to use these attributes today, whether or not your target browser supports them. This is because the attributes will be safely ignored by any browser on the market today if the browser does not understand them.
The placeholder Attribute
The placeholder attribute gives input controls an easy way to provide descriptive, alternate hint text which is shown only when the user has not yet entered any values. This is common in many modern user interface frameworks, and popular JavaScript frameworks have also provided emulation of this feature. However, modern browsers have it built-in.
To use this attribute, simply add it to an input with a text representation. This includes the basic text type, as well as the semantic types such as email, number, url, etc.
<label>Runner: <input name="name" placeholder="First and last name"></label>
In a modern browser, this causes the field to display a faint version of the placeholder text which will disappear whenever the user or application puts focus into the field, or whenever there is a value present.
The same attribute, when running in a non-supporting browser, will just be ignored, causing the default field behavior to display.
Similarly, whenever a value is entered in the field, the placeholder text will not appear.
200
CHAPTER 8 USING THE FORMS API
The autocomplete Attribute
The autocomplete attribute, introduced in Internet Explorer 5.5, has finally been standardized. Hooray! (Browsers have been supporting the attribute for nearly as long as its inception, but having a specified behavior helps everyone.)
The autocomplete attribute tells the browser whether or not the value of this input should be saved for future. For example:
<input type="text" name="creditcard" autocomplete="off">
The autocomplete attribute should be used to protect sensitive user data from insecure storage in the local browser files. Table 8-3 shows the different behavior types.
Table 8-3. Autocomplete Behavior in Input Controls
Type |
Purpose |
on |
The field is not secure, and its value can be saved and restored. |
off |
The field is secure, and its value should not be saved. |
unspecified |
Default to the setting on the containing <form>. If not contained in a form, or no value is |
|
set on the form, then behave as if on. |
|
|
The autofocus Attribute
The autofocus attribute lets a developer specify that a given form element should take input focus immediately when the page loads. Only one attribute per page should specify the autofocus attribute. Behavior is undefined if more than one control is set to autofocus.
Note Only one autofocus control per page is difficult to achieve if your content is being rendered into a portal or shared content page. Do not rely on autofocus if you are not in complete control of the page.
To set the focus automatically to a control such as a search text field, simply set the autofocus attribute on that element alone:
<input type="search" name="criteria" autofocus>
Like other boolean attributes, no value needs to be specified for the true case.
201
CHAPTER 8 USING THE FORMS API
Note Autofocus can annoy users if they are not expecting a focus change. Many users utilize keystrokes for navigation, and switching focus to a form control subverts that ability. Use it only when it is a given that a form control should take all default keys.
The spellcheck Attribute
The spellcheck attribute can be set on input controls with text content, as well as the textarea. When set, it suggests to the browser whether or not spelling feedback should be given. A normal representation of this element is to draw a red dotted line under text that does not map any entry in the currently set dictionary. This hints to the user to double-check the spelling or to get a suggestion from the browser itself.
Note that the spellcheck attribute needs a value. You can’t just set the attribute alone on the element.
<textarea id=”myTextArea” spellcheck=”true”>
Also note that most browsers will default to leaving the spellcheck on, so unless the element (or one of its parent elements) turns off spellchecking, it will display by default.
The list Attribute and the datalist Element
The list attribute and datalist element combine to let a developer specify a list of possible values for an input. To use this combination:
1.Create a datalist element in your document with its id set to a unique value. The datalist can be located anywhere in the document.
2.Populate the datalist with as many option elements as needed to represent the full set of suggestions for values of a control. For example, a datalist representing e-mail contacts should contain all of the contact e-mail addresses as individual option children.
<datalist id="contactList">
<option value="x@example.com" label="Racer X"> <option value="peter@example.com" label="Peter">
</datalist>
3.Link the input element to the datalist by setting the list attribute to a value which is the id of the associated datalist.
<input type="email" id="contacts" list="contactList">
On a supporting browser this produces a customized list control like the following:
202
CHAPTER 8 USING THE FORMS API
The min and max Attributes
As seen before in our example for <input type="range">, the min and max attributes allow a numerical input to be constrained to minimum and maximum values. One, both, or neither of these attributes can be provided as necessary, and the input control should adjust accordingly to increase or decrease the range of acceptable values. For example, to create a range control representing a level of confidence in ability from zero% to 100%, the following code could be used as follows:
<input id="confidence" name="level" type="range" min="0" max="100" value="0">
This would create a range control with a minimum zero value and maximum of 100, which, coincidentally, are the default values for the same.
The step Attribute
Also, for input types which expect numerical values, the step attribute specifies the granularity of increments or decrements in value as the range is adjusted. For example, our confidence level range control listed above can be set up with a step attribute of five as follows:
<input id="confidence" name="level" type="range" min="0" max="100" step="5" value="0">
This would limit the acceptable values to be increments of five from the starting value. In other words, only 0, 5, 10, 15, … 100 would be allowed either through typed input or through a slider control, depending on the browser representation of the input.
The default step value is dependent on the type of control to which it is applied. For a range input, the default step is one. To accompany the step attribute, HTML5 introduces two functions on the input element that allow the value to be controlled: stepUp and stepDown.
As you might expect, these functions increment or decrement the current value, respectively. As you might also expect, the amount by which the value is increased or decreased is the value of the step. As such, the value of a numeric input control can be tweaked without direct input from the user.
The valueAsNumber Function
The new valueAsNumber function is a handy way to convert the value of a control from text to number… and back! That is the case because the valueAsNumber is both a getter and a setter function. When called as a getter, the valueAsNumber function converts the text value of an input field into a number type upon which calculations are allowed. If the text value does not cleanly convert into a number type, then the NaN value (Not-a-Number) is returned.
The valueAsNumber can also be used to set the value of an input to a numeric type. For example, our confidence range could be set using a call such as:
document.getElementById("confidence").valueAsNumber(65);
Make sure the number meets the requirements of the min, max, and step, or an error will be thrown.
The required Attribute
If any input control has the required attribute set, then a value must be set on it before its form can be submitted. For example, to set a text input field as required, simply add the attribute as shown here:
203