Describing Data with New Input Fields

HTML5 introduces several new input types that you can use to better describe the type of data your users are entering. In addition to the standard text fields, radio buttons, and checkbox elements, you can use elements such as email fields, calendars, color pickers, spinboxes, and sliders. Browsers can use these new fields to display better controls to the user without the need for JavaScript. Mobile devices and virtual keyboards for tablets and touchscreens can use the field types to display different keyboard layouts. For example, the iPhone’s Mobile
Safari browser displays alternate keyboard layouts when the user is entering data into the URL and email types, making special characters like (@), (7), (7), and [/) easily accessible.

Improving the AwesomeCo Projects Form

AwesomeCo is working on creating a new project management web application to make it easier for developers and managers to keep up with the progress of the many projects they have going on. Each project has a name, a contact email address, and a staging URL so managers can preview the website as it’s being built. There are also fields for the start date, priority, and estimated number of hours the project should take to complete. Finally, the development manager would like to give each project a color so he can quickly identify each project when he looks at reports.

Let’s mock up a quick project preferences page using the new HTML5 fields.

Setting Up the Basic Form

Let’s create a basic HTML form that does a POST request. Since there’s nothing special about the name field, we’ll use the trusty text field.

<form method=”post” action=”/projects/l”>
<fieldset id=”personal_information”>
<1egend>Proj ect Information</legencb<ol>
<label for=”name”>Name</label>
<input type=”text” name=”name” autofocus id=”name”>
<input type=”submit” value=”Submit”>

Notice that we are marking this form up with labels wrapped in an ordered list. Labels are essential when creating accessible forms. The for attribute of the label references the id of its associated form element. This helps screen readers identify fields on a page. The ordered list
provides a good way of listing the fields without resorting to complex table or div structures. This also gives you a way to mark up the order in which you’d like people to fill out the fields.

Creating a Slider Using Range

Sliders are commonly used to let users decrease or increase a numerical value and could be a great way to quickly allow managers to both visualize and modify the priority of the project. You implement a slider with the range type.

<label for=”priority”>Priori ty</label>
<input type= “range” min=”0″ max= “10”
name= “priority” value=”0″ id =”priority”>

Add this to the form, within a new li element just like the previous field. Chrome and Opera both implement a Slider widget, which looks like this:


Notice that we’ve also set the min and max range for the slider. That will constrain the value of the form field.

Handling Numbers with Spinboxes

We use numbers a lot, and although typing numbers is fairly simple, spinboxes can make making minor adjustments easier. A spinbox is a control with arrows that increment or decrement the value in the box. Let’s use the spinbox for estimated hours. That way, the hours can be easily adjusted.

<label for=”estimated_hours”>Estimated Hours</label>
<input type=”number” name=”estimated_hours”
min=”0″ max=”1000″
i d=”estimated_hours”>

Opera supports the spinbox control, which looks like this:

Estimated Hours

The spinbox also allows typing by default, and like range sliders, we can set minimum and maximum values. However, those minimum and maximum ranges won’t be applied to any value you type into the field. Also notice that you can control the size of the increment step by giving
a value to the step parameter. It defaults to 1 but can be any numerical value.


Recording the start date of the project is pretty important, and we want to make that as easy as possible. The date input type is a perfect fit here.

<label for=”start_date”>Start date</label>
<input type= “date” name=”start_date” id =”start_date”

At the time of writing, Opera is the only browser that currently supports a full calendar picker.

Here’s an example of its implementation:

Safari 5.0 displays a field similar to the number field with arrows to increment and decrement the date. It defaults to “1582” if left blank. Other browsers render a text field.


The HTML5 specification says that the email input type is designed to hold either a single email address or an email address list, so that’s the perfect candidate for our email field.

<label for=”email”>Emai 1 contact</label>
<input type=”email” name=”email” id=”email”>

Mobile devices get the most benefit from this type of form field, because the virtual keyboard layouts change to make entering email addresses easier.

There’s a field type designed to handle URLs too. This one is especially nice if your visitor uses an iPhone, because it displays a much different keyboard layout, displaying helper buttons for quickly entering web addresses, similar to the keyboard displayed when entering a URL into Mobile Safari’s address bar. Adding the staging URL field is as simple as adding this code:

<label for=”url”»Staging URL</label>
<input type=”url” name=”url” id=”url”>

Virtual keyboards use this field type to display a different layout as well.

Figure 3.1: Some form controls are already supported in Opera.


Finally, we need to provide a way to enter a color code, and we’ll use the color type for that.

<label for=”project_color”>Project color</label>
<input type=”color” name=”project_color” id=”project_color”>

At the time of writing, no browsers display a color picker control, but that shouldn’t stop you from using this field. You’re using proper markup to describe your content, and that’s going to come in handy in the future, especially when you need to provide fallback support.

Opera supports most of these new controls right now, as you can see in Figure 3.1, but when you open the page in Firefox, Safari, or Google Chrome, you won’t see much of a difference. We’ll need to fix that.

Falling Back

Browsers that don’t understand these new types simply fall back to the text type, so your forms will still be usable. At that point, you can bind one of the jQuery UI or YUI widgets to that field to transform it. As time goes on and more browsers support these controls, you can remove the JavaScript hooks.

Replacing the Color Picker

We can easily identify and replace the color picker using jQuery with CSS3’s attribute selectors. We locate any input field with the type of color and apply a jQuery plug-in called SimpleColor.

if (!hasColorSupportO){
$C’input[type=color]’) .simpleColorO ;

Since we used the new form types in our markup, we don’t have to add an additional class name or other markup to identify the color pickers. Attribute selectors and HTML5 go together quite well.

We don’t want to use this color picker plug-in if the browser has native support for it, so we will use some JavaScript to detect whether the browser supports input fields with a type of color.

Une l function hasColorSupport(){
input = document.createElementC”input”) ;
input.setAttributeC”type”, “co7or”) ;
var hasColorType = (input.type !== “text”);
5 // handle Safari/Chrome partial implementation
var testString = “foo”;
i nput.value=testStri ng;
hasColorType = (input.value != testString);
10 }

First, we use plain JavaScript to create an element and set its type attribute to color. Then, we retrieve the type attribute to see whether the browser allowed us to set the attribute. If it comes back with a value of color, then we have support for that type. If not, we’ll have to apply our script.

Things get interesting on line 6. Safari 5 and Google Chrome 5 have partially implemented the color type. They support the field, but they don’t actually display a color widget. We still end up with a text field on the page. So, in our detection method, we set the value for our input field and see whether the value sticks around. If it doesn’t, we can assume that the browser has implemented a color picker because the input field isn’t acting like a text box.

The whole bit of code to replace the color picker looks like this:

if (!hasColorSupportO){
$C’input[type=color]’) .simpleColorO ;

That solution works, but it’s very brittle. It targets a specific set of browsers and only for the color control. Other controls have their own quirks that you need to learn. Thankfully, there’s an alternative solution.


The Modernizr2 library can detect support for many HTML5 and CSS3 features. It doesn’t add the missing functionality, but it does provide several mechanisms similar to the solution we implemented for detecting form fields that are more bulletproof.

Before you start throwing Modernizr in your projects, be sure you take some time to understand how it works. Whether you wrote the code yourself or not, if you use it in your project, you’re responsible for it. Modernizr wasn’t ready to handle Safari’s partial support of the color field right away. When the next version of Chrome or Firefox comes out, you may have to hack together a solution. Who knows, maybe you’ll beable to contribute that solution back to Modernizr!

You’ll implement fallbacks for controls such as the date picker and the slider in the same manner. Sliders and date pickers are included as components in the jQuery UI library.3 You’ll include the jQuery UI library on the page, detect whether the browser supports the control
natively, and, if it doesn’t, apply the JavaScript version instead.

Eventually you’ll be able to phase out the JavaScript controls and rely completely on the controls in the browser. Because of the complexity involved with detecting these types, Modernizer will be very helpful to you. However, we’ll continue writing our own detection techniques throughout the rest of this book so you can see how they work.

Aside from new form field types, HTML5 introduces a few other attributes for form fields that can help improve usability. Let’s take a look at autofocus next.

Creating User-Friendly Web Forms

If you’ve ever designed a complicated user interface, you know how limiting the basic HTML form controls are. You’re stuck using text fields, select menus, radio buttons, checkboxes, and sometimes the even clunkier multiple select lists that you constantly have to explain to your users how to use. (“Hold down the Ctrl key and click the entries you want, unless you’re on a Mac, in which case use the Cmd key.”)

So, you do what all good web developers do—you turn to Prototype or j Query, or you roll your own controls and features using a combination of HTML, CSS, and JavaScript. But when you look at a form that has sliders, calendar controls, spinboxes, autocomplete fields, and visual
editors, you quickly realize that you’ve created a nightmare for yourself. You’ll have to make sure that the controls you include on your page don’t conflict with any of the other controls you’ve included or any of the other JavaScript libraries on the page. You can spend hours implementing a calendar picker only to find out later that now the Prototype library is having problems because jQuery took over the $() function. So, you use jQuery’s noConflictO method, but then you find out that the color picker control you used no longer works because that plug-in wasn’t written carefully enough.

If you’re smiling, it’s because you’ve been there. If you’re fuming, I’m guessing it’s for the same reason. There is hope, though. In this chapter, we’re going to build a couple of web forms using some new form field types, and we’ll also implement autofocusing and placeholder text.

Finally, we’ll discuss how to use the new contenteditable attribute to turn any HTML field into a user input control. Specifically, we’ll cover the following features:

Email field [<input type=”email”>]
Displays a form field for email addresses. [Ol 0.1, IOS]
URL field [<input type=”url”>]
Displays a form field for URLs. [OlO.l, IOS]
Telephone field [<input type=”tel”>]
Displays a form field for telephone numbers. [OlO.l, IOS]
Search field [<input type=”search”>
Displays a form field for search keywords. [C5, S4, OlO.l, IOS]
Slider (range) [<input type=”range”>]
Displays a slider control. [C5, S4, OlO.l]
Number [<input type=”number”>]
Displays a form field for numbers, often as a spinbox. [C5, S5,OlO.l, IOS]
Date fields [<input type=”date”>]
Displays a form field for dates. Supports date, month, or week. [C5,S5, OlO.l]
Dates with Times [<input type=”datetime”>]
Displays a form field for dates with times. Supports datetime,
datetime-local, or time. [C5, S5, OlO.l]
Color [<input type=”color”>]
Displays a field for specifying colors. [C5, S5] (Chrome 5 and Safari
5 understand the Color field but do not display any specificcontrol.)
Autofocus support [<input type=”text” autofocus>]
Support for placing the focus on a specific form element. [C5, S4]

Placeholder support [<input type=”email”  placeholder=”[email protected]”>]
Support for displaying placeholder text inside of a form field. [C5,S4, F4]
In-place editing support [<p contenteditable>lorem ipsum</p>]
Support for in-place editing of content via the browser. [C4, S3.2,IE6, OlO.l]

Let’s start by learning about some of the extremely useful form field types.

Creating Pop-up Windows with Custom Data Attributes

If you’ve built any web application that uses JavaScript to grab information out of the document, you know that it can sometimes involve a bit of hackery and parsing to make things work. You’ll end up inserting extra information into event handlers or abusing the rel or class attributes to inject behavior. Those days are now over thanks to the introduction of custom data attributes.

Custom data attributes all start with the prefix data- and are ignored by the validator for HTML5 documents. You can attach a custom data attribute to any element you’d like, whether it be metadata about a photograph, latitude and longitude coordinates, or, as you’ll see in this tip, dimensions for a pop-up window. Best of all, you can use custom data attributes right now in nearly every web browser, since they can be easily grabbed with JavaScript.

Separating Behavior from Content, or Why onclick Is Bad
Over the years, pop-up windows have gotten a bad reputation, and often rightly so. They’re often used to get you to look at an ad, to convince unsuspecting web surfers to install spyware or viruses, or, worse, to give away personal information that is then resold. It’s no wonder most browsers have some type of pop-up blocker available.

Pop-ups aren’t all bad, though. Web application developers often rely on pop-up windows to display online help, additional options, or other important user interface features. To make pop-ups less annoying, we
need to implement them in an unobtrusive manner. When you look at AwesomeCo’s human resources page, you see several links that display policies in pop-up windows. Most of them look like this:

<a href=’#’
onclick=”‘holiday_pay.html’,WinName, ‘width=300,height=300);”>
Holiday pay

This is a pretty common way to build links that spawn pop-ups. In fact, this is the way JavaScript newbies often learn how to make pop-up windows. There are a couple of problems that we should address with this approach before moving on, though.

Improve Accessibility

The link destination isn’t set! If JavaScript is disabled, the link won’t take the user to the page. That’s a huge problem we need to address immediately. Do not ever omit the href attribute or give it a value like this under any circumstances. Give it the address of the resource that would normally pop up.

<a href=’holiday_pay.html’
oncl i ck= “window. open(this.href, WinName, ‘width=300, height=300) ; “>
Holiday pay

The JavaScript code then reads the attached element’s href attribute for the link’s location.

The first step toward building accessible pages is to ensure that all the functionality works without JavaScript.

Abolish the onclick

Keep the behavior separate from the content, just like you keep the presentation information separate by using linked style sheets. Using onclick is easy at first, but imagine a page with fifty links, and you’ll see how the onclick method gets out of hand. You’ll be repeating that
JavaScript over and over again. And if you generate this code from some server-side code, you’re just increasing the number of JavaScript events and making the resulting HTML much bigger than it needs to be.

Instead, give each of the anchors on the page a class that identifies them.

<a href=”holiday_pay”>Holiday Pay</a>

var links = $(“a.popup”) ]
1 i nks.cli ck(function(event){
event.preventDefault() ;$(this).attrC’href’));
} ) ;

We use a jQuery selector to grab the element with the class of popup, and then we add an observer to each element’s click event. The code we pass to the click method will be executed when someone clicks the link. The preventDefault method prevents the default click event behavior. In this case, it prevents the browser from following the link and displaying a new page.

One thing we’ve lost, though, is the information on how to size and position the window, which is something we had in the original example. We want a page designer who isn’t that familiar with JavaScript to still be able to set the dimensions of a window on a per-link basis.

Custom Data Attributes to the Rescue!

Situations like this are common when building any JavaScript-enabled application. As we’ve seen, storing the window’s desired height and width with the code is desirable, but the onclick approach has lots of drawbacks. What we can do instead is embed these attributes as  attributes on the element. All we have to do is construct the link like this:

<a href=”he!p/holi day_pay.html”
title=”Holiday Pay”
cl ass=”popup”>Holiday pay</a>

Now we just modify the click event we wrote to grab the options from the custom data attributes of the link and pass them to the method.

$( “.popup”) . cl i ckCfuncti on (event) {
event.preventDefaul t();
var href = $(this) .attr(“href”) ;
var width = $(this) ,attr(“data-width”) ;
var height = $(this).attr(“data-height”) ;
var popup = (href,”popup”,
“height=” + height +”,width=” + width + “”);
} ) ;

That’s all there is to it! The link now opens in a new window.

A Word of Caution

In this example, we used custom data attributes to provide additional information to a client-side script. It’s a clever approach to a specific problem and Illustrates one way to use
these attributes. It does tend to mix presentation Information with our markup, but it’s a simple way to show you how easy It is to use JavaScript to read values you embed in your page.

Falling Back

These attributes work in older browsers right now as long as they support JavaScript. The custom data attributes won’t trip up the browser, and your document will be valid since you’re using the HTML5 doctype, since the attributes that start with data- will all be ignored.

The Future

We can do some interesting things with these new tags and attributes once they’re widely supported. We can identify and disable navigation and article footers very easily using print style sheets,

nav, arti cle>footer{di splay:none}

We can use scripting languages to quickly identify all of the articles on a page or on a site. But most important, we mark up content with appropriate tags that describe it so we can write better style sheets and better JavaScript.

Custom data attributes give developers the flexibility to embed all sorts of information in their markup.

You can use them with JavaScript to determine whether a form tag should submit via Ajax, by simply locating any form tag with dataremote= true, which is something that the Ruby on Rails framework is doing.

You can also use them to display dates and times in a user’s time zone while still caching the page. Simply put the date on the HTML page as UTC, and convert it to the user’s local time on the client side. These attributes allow you to embed real, usable data in your pages, and you can expect to see more and more frameworks and libraries taking advantage of them. I’m sure you’ll find lots of great uses for them in your own work.

And we can help wipe out Divitis once and for all!

Redefining a Blog Using Semantic Markup

One place you’re sure to find lots of content in need of structured markup is a blog. You’re going to have headers, footers, multiple types of navigation (archives, blogrolls, and internal links), and, of course, articles or posts. Let’s use HTML5 markup to mock up the front page of
the blog for AwesomeCo, a company on the cutting edge of Awesomeness.

To get an idea of what we’re going to build, take a look at Figure 2.1, on the following page. It’s a fairly typical blog structure, with a main header with horizontal navigation below the header. In the main section, each article has a header and a footer. An article may also have a pull quote, or an aside. There’s a sidebar that contains additional navigation elements. Finally, the page has a footer for contact and copyright information. There’s nothing new about this structure, except that this time, instead of coding it up with lots of div tags, we’re going to use specific tags to describe these regions.

It All Starts with the Right Doctype

We want to use HTML5’s new elements, and that means we need to let browsers and validators know about the tags we’ll be using. Create a new page called index.html, and place this basic HTML5 template into that file.

Line l <!D O C T Y P E h t m l >
2 <html lang=”en-US”>
3 <head>
4 <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
5 <title>AwesomeCo Blog</title>
6 </head>
8 <body>
9 </body>
10 </html>

blog structure using HTML5

Take a look at the doctype on line 1 of that example. This is all we
need for an HTML5 doctype. If you’re used to doing web pages, you’re
probably familiar with the long, hard-to-remember doctypes for XHTML
like this:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”””>

Now, take another look at the HTML5 doctype:


That’s much simpler and much easier to remember.

The finished layout

The point of a doctype is twofold. First, it’s to help validators determine
what validation rules it needs to use when validating the code. Second,
a doctype forces Internet Explorer versions 6, 7, and 8 to go into
“standards mode,” which is vitally important if you’re trying to build
pages that work across all browsers. The HTML5 doctype satisfies both
of these needs and is even recognized by Internet Explorer 6.


Headers, not to be confused with headings such as hi, h2, and h3, may
contain all sorts of content, from the company logo to the search box.
Our blog header will contain only the blog’s title for now.

Une l <header id=”page_header”>
2 <hl>AwesomeCo Blog!</hl>
3 </header>

You’re not restricted to having just one header on a page. Each individual
section or article can also have a header, so it can be helpful to
use the ID attribute like I did on 1 to uniquely identify your elements. A
unique ID makes it easy to style elements with CSS or locate elements
with JavaScript.

Semantic markup is all about describing your content. If you’ve
been developing web pages for a few years, you’ve probably
divided your pages Into various regions such as header, footer,
and sidebar so that you could more easily identify the regions of
the page when applying style sheets and other formatting.
Semantic markup makes It easy for machines and people alike
to understand the meaning and context of the content. The
new HTML5 markup tags such as section, header, and nav help
you do just that.


The footer element defines footer information for a document or an adjacent
section. You’ve seen footers before on websites. They usually contain
information like the copyright date and information on who owns
the site. The specification says we can have multiple footers in a document
too, so that means we could use the footers within our blog
articles too.

For now, let’s just define a simple footer for our page. Since we can
have more than one footer, we’ll give this one an ID just like we did with
the header. It’ll help us uniquely identify this particular footer when we
want to add styles to this element and its children.

<footer id=”page_footer”>
<p>&copy; 2010 AwesomeCo.</p>

This footer simply contains a copyright date. However, like headers,
footers on pages often contain other elements, including navigational


Navigation is vital to the success of a website. People simply aren’t going
to stick around if you make it too hard for them to find what they’re
looking for, so it makes sense for navigation to get its own HTML tag.

Let’s add a navigation section to our document’s header. We’ll add links
to the blog’s home page, the archives, a page that lists the contributors
to the blog, and a link to a contact page.

Une l <header id=”page_header”>
<hl>AwesomeCo Blog!</hl>
5 <lixa href=”/”>Latest Posts</ax/l i>
<1 i x a href=”archives”>Archi ves</ax/l i>
<1 i x a href=”contributors”>Contri butors</ax/l i>
< l i x a href=”contact”>Contact Us</ax/li>
io </nav>

Like headers and footers, your page can have multiple navigation elements.
You often find navigation in your header and in your footer, so
now you can identify those explicitly. Our blog’s footer needs to have
links to the AwesomeCo home page, the company’s “about us” page,
and links to the company’s terms of service and privacy policies. We’ll
add these as another unordered list within the page’s footer element.

<footer id=”page_footer”>
<p>&copy; 2010 AwesomeCo.</p>
<1 i x a href=””>Home</ax/l i>
<1 i x a href=”about”>About</ax/l i>
< l i x a href=”terms.html”>Terms of Servi ce</ax/l i>
<1 i x a href=”privacy.html “>Pri vacy</ax/l i>

We will use CSS to change how both of these navigation bars look, so
don’t worry too much about the appearance yet. The point of these new
elements is to describe the content, not to describe how the content

Sections and Articles

Sections are the logical regions of a page, and the section element is
here to replace the abused div tag when it comes to describing logical
sections of a page.

<section id=”posts”>

Don’t get carried away with sections, though. Use them to logically
group your content! Here we’ve created a section that will hold all the
blog posts. However, each post shouldn’t be in its own section. We have
a more appropriate tag for that.


The article tag is the perfect element to describe the actual content
of a web page. With so many elements on a page, including headers,
footers, navigational elements, advertisements, widgets, blogrolls, and
social media bookmarks, it might be easy to forget that people come
to your site because they’re interested in the content you’re providing.
The article tag helps you describe that content.

Each of our articles will have a header, some content, and a footer. We
can define an entire article like this:

<h2>How Many Should We Put You Down For?</h2>
<p>Posted by Brian on
<time datetime=”2010-10-01T14:39″>0ctober 1st, 2010 at 2:39PM</time>
The first big rule in sales is that if the person leaves empty-handed,
they’re likely not going to come back. That’s why you have to be
somewhat aggressive when you’re working with a customer, but you have
to make sure you don’t overdo it and scare them away.
One way you can keep a conversation going is to avoid asking questions
that have yes or no answers. For example, if you’re selling a service
plan, don’t ever ask &quot;Are you interested in our 3 or 5 year
service plan?&quot; Instead, ask &quot;Are you interested in the 3
year service plan or the 5 year plan, which is a better value?&quot;
At first glance, they appear to be asking the same thing, and while
a customer can still opt out, it’s harder for them to opt out of
the second question because they have to say more than just
< p x a href=”comments”xi>2 5 Comments</ix/a> . . .</p>

We can use header and footer elements inside of our articles, which
makes it much easier to describe those specific sections. We can also
divide our article into multiple sections using the section element.

Asides and Sidebars

Sometimes you have content that adds something extra to your main
content, such as pullout quotes, diagrams, additional thoughts, or related
links. You can use the new aside tag to identify these elements.

&quot;Never give someone a chance to say no when
selling your product.&quot;

We’ll place the callout quote in an aside element. We’ll nest this aside
within the article, keeping it close to its related content.

Our completed section, with the aside, looks like this:

<section id=”posts”>
<h2>How Many Should We Put You Down For?</h2>
<p>Posted by Brian on
<time datetime=”2010-10-01T14:39″>0ctober 1st, 2010 at 2:39PM</time>
&quot;Never give someone a chance to say no when
selling your product.&quot;
The first big rule in sales is that if the person leaves empty-handed,
they’re likely not going to come back. That’s why you have to be
somewhat aggressive when you’re working with a customer, but you have
to make sure you don’t overdo it and scare them away.
One way you can keep a conversation going is to avoid asking questions
that have yes or no answers. For example, if you’re selling a service
plan, don’t ever ask &quot;Are you interested in our 3 or 5 year
service plan?&quot; Instead, ask &quot;Are you interested in the 3
year service plan or the 5 year plan, which is a better value?&quot;
At first glance, they appear to be asking the same thing, and while
a customer can still opt out, it’s harder for them to opt out of
the second question because they have to say more than just
< p x a href=”comments”xi>2 5 Comments</ix/a> . . .</p>

Now we just have to add the sidebar section.

Asides Are Not Page Sidebars!

Our blog has a sidebar on the right side that contains links to the
archives for the blog. If you’re thinking that we could use the aside
tag to define the sidebar of our blog, you’d be wrong. You could do it
that way, but it goes against the spirit of the specification. The aside is designed to show content related to an article. It’s a good place to show
related links, a glossary, or a pull out quote.

To mark up our sidebar that contains our list of prior archives, we’ll
just use another section tag and a nav tag.

<section id=”sidebar”>
<1 i x a href=”2010/10″>0ctober 2010</ax/l i>
<1 i x a href=”2010/09″>September 2010</ax/li>
<1 i x a href=”2010/08″>August 2010</ax/li>
<1 i x a href=”2010/07″>July 2010</ax/li>
<1 i x a href=”2010/06″>June 2010</ax/li>
<1 i x a href=”2010/05″>May 2010</ax/li>
<1 i x a href=”2010/04″>Apri 1 2010</ax/li>
<1 i x a href=”2010/03″>March 2010</ax/li>
<1 i x a href=”2010/02″>February 2010</ax/li>
<1 i x a href=”2010/01″>January 2010</ax/li>

That’s it for our blog’s structure. Now we can start applying styles to
these new elements.


We can apply styles to these new elements just like we’d style div tags.
First, we create a new style sheet file called style.ess and attach it to our
HTML document by placing a style sheet link in the header, like this:

<link rel=”stylesheet” href=”style.ess” type=”text/css”>

Let’s first center the page’s content and set some basic font styles.

margin:15px auto;
font-family: Arial, “MS Trebuchet”, sans-serif;
margin:0 0 20px 0;

P, 1 U

Next, we define the header’s width.


We style the navigation links by transforming the bulleted lists into
horizontal navigation bars.

header#page_header nav ul, #page_footer nav ul{
list-style: none;
margin: 0;
padding: 0;
#page_header nav ul li, footer#page_footer nav ul li{
margin: 0 20px 0 0;
display ¡inline;

The posts section needs to be floated left and given a width, and we also
need to float the callout inside the article. While we’re doing that, let’s
bump up the font size for the callout.

float: left;
width: 74%;
section#posts aside{
float: right;
width: 35%;
margin-left: 5%;
font-size: 20px;
line-height: 40px;

We’ll also need to float the sidebar and define its width.

float: left;
width: 2 5%;

If you need to implement a pledge meter or an upload
progress bar in a web application, you should investigate the
meter and progress elements introduced in HTML5.
The meter element lets us semantically describe an actual fixed
point on a meter with a minimum and maximum value. For your
meter to be in harmony with the specification, you shouldn’t
use your meter for things with arbitrary minimum or maximum
values like height and weight, unless you are talking about
something specific where you have set a specific boundary.
For example, if we have a fundraising website and we want to
show how close we are to our goal of $5,000, we can describe
that easily:

<section id=”pledge”>
<h3>0ur Fundraising Goal</h3>
<meter ti tl e= “L/SD” id=”pledge_goal ”
value= “2500” min=”0″ max= “5000”>
<p>Help us reach our goal of $5000!</p>

The progress element is very similar to a meter, but it’s designed
to show active progress like you’d see if you were uploading a
file. A meter, by comparison, is designed to show a measurement
that’s not currently moving, like a snapshot of available
storage space on the server for a given user. The markup for a
progress bar is very similar to the meter element.

<progress id=”progressbar” max=100xspan>0</span>%</progress>

The meter and progress elements aren’t styled by any browsers
yet, but you can use JavaScript to grab the values in the meter
and build your own visualization, using the meter or progress to
semantically describe the data. You can see an example of
how you might do that by looking at the book’s example files
for the meter element.

And we need to define the footer. We’ll clear the floats on the footer so
that it sits at the bottom of the page.

clear: both;
width: 100%;
display: block;
text-align: center;

These are just basic styles. From here, I’m confident you can make this
look much, much better.

Falling Back

Although this all works great in Firefox, Chrome, and Safari, the people
in management aren’t going to be too happy when they see the mess
that Internet Explorer makes out of our page. The content displays fine,
but since IE doesn’t understand these elements, it can’t apply styles to
them, and the whole page resembles something from the mid-1990s.
The only way to make IE style these elements is to use JavaScript to
define the elements as part of the document. That turns out to be really
easy. We’ll add this code to our head section of the page so it executes
before the browser renders any elements. We’ll place it inside a conditional
comment, a special type of comment that only Internet Explorer
will read.

<! — [i f It IE 9]>
<script type=”text/javascript”>
document.createElementC”section”) ;
document.createElementC”article”) ;
</scri pt>

This particular comment targets any version of Internet Explorer older
than version 9.0. If we reload our page, it looks correct now.
We are creating a dependency on JavaScript, though, so you need to
take that into consideration. The improved organization and readability of the document make it worth it, and since there are no accessibility
concerns, because the contents still display and are read by a screen
reader, you’re only making the presentation seem grossly out-of-date to
your users who have disabled JavaScript intentionally.
This approach is fine for adding support for a handful of elements or for
understanding how you can add support. Remy Sharp’s brilliant HTMLShiv3
takes this approach much further and might be more appropriate
for incorporating fallback support if you’re looking to support many
more elements.

New Structural Tags and Attributes

In the first few chapters of this book, we’ll talk about how we can use HTML5’s and CSS’s features to improve the interfaces we present to our users. We’ll see how we can create better forms, easily style tables, and improve the accessibility of our pages for assistive devices. We’ll also see how we can use content generation to improve the usability of our print style sheets, and we’ll explore in-place editing with the new contenteditable attribute. First, though, let’s take a look at how HTML5’s new elements can help us structure our pages better.

I’d like to talk to you about a serious problem affecting many web developers today. Divitis—a chronic syndrome that causes web developers to wrap elements with extra div tags with IDs such as banner, sidebar, article, and footer—is rampant. It’s also highly contagious.  Developers pass Divitis to each other extremely quickly, and since divs are invisible to the naked eye, even mild cases of Divitis may go unnoticed for years.

Here’s a common symptom of Divitis:

<div id=”navbar_wrapper”>
<div id=”navbar”>
<1 i ><a h ref = “/”>Home</ax/l i >
<1 i ><a h ref = “/”>Home</ax/l i >

Here we have an unordered list, which is already a block element,1 wrapped with two div tags that are also block elements. The id attributes on these wrapper elements tell us what they do, but you can remove at least one of these wrappers to get the same result. Overuse of markup
leads to bloat and pages that are difficult to style and maintain.

There is hope, though. The HTML5 specification provides a cure in the form of new semantic tags that describe the content they contain. Because so many developers have made sidebars, headers, footers, and sections in their designs, the HTML5 specification introduces new tags specifically designed to divide a page into logical regions. Let’s put those new elements to work. Together with HTML5, we can help wipe out Divitis in our lifetime.

In addition to these new structural tags, we’ll also talk about the meter element and discuss how we can use the new custom attributes feature in HTML5 so we can embed data into our elements instead of hijacking classes or existing attributes. In a nutshell, we’re going to find out how to use the right tag for the right job.

In this chapter, we’ll explore these new elements and features:

Defines a header region of a page or section. [C5, F3.6, IE8, S4,
Defines a footer region of a page or section. [C5, F3.6, IE8, S4, Ol 0]
Defines a navigation region of a page or section. [C5, F3.6, IE8, S4,
Defines a logical region of a page or a grouping of content. [C5,
F3.6, IE8, S4, 010]

Defines an article or complete piece of content. [C5, F3.6, IE8, S4,
Defines secondaiy or related content. [C5, F3.6, IE8, S4, 010]
Custom data attributes
Allows addition of custom attributes to any elements using the
data- pattern. [All browsers support reading these via JavaScript’s
getAttributeO method.]
Describes an amount within a range. [C5, F3.5, S4, 010]
Control that shows real-time progress toward a goal. [Unsupported
at publication time.]

The Road to the Future Is Bumpy

Our users must be able to interact with our websites, whether they are
visually impaired, hearing impaired, on older browsers, on slow connections,
or on mobile devices. HTML5 introduces some new elements,
such as audio, video, and canvas. Audio and video have always had
accessibility issues, but the canvas element presents new challenges.
The canvas element lets us create vector images within the HTML document
using JavaScript. This creates issues for the visually impaired but
also causes problems for the 5 percent of web users who have disabled

There are a few roadblocks that continue to impede the widespread adoption of HTML5 and CSS3. Some are obvious, and some are less so.

y/ Joe Asks…
^ But I Like My XHTML Self-Closing Tags. Can I Still Use Them?

You sure can! Many developers fell In love with XHTML because of the stricter requirements on markup. XHTML documents forced quoted attributes, made you self-close content tags, required that you use lowercase attribute names, and brought well-formed markup onto the World Wide Web. Moving to HTML5 doesn’t mean you have to change your ways. HTML5 documents will be valid If you use the HTML5-style syntax or the XHTML syntax, but you need to understand the Implications of using self-closing tags.

Most web servers serve HTML pages with the text/html MIME type because of Internet Explorer’s Inability to properly handle the application/xml+xhtml MIME type associated with XHTML pages. Because of this, rowsers tend to strip off self-closing tags because self-closing tags were not considered valid HTML before HTML5. For example, if you had a self-closing script tag above a div like this:

<script language=”javascript” src=”app1ication.js” />

the browser would remove the self-closing forward slash, and then the renderer would think  that the h2 was within the script tag, which never closes! This is why you see script tags  coded with an explicit closing tag, even though a self-closing tag is valid XHTML markup.

So, be aware of possible issues like this if you do use selfclosing tags In your HTML5 documents, because they will be served with the text/html MIME type. You can learn more about this Issue and others at

Cake and Frosting

I like cake. I like pie better, but cake Is pretty good stuff. I prefer
cake with frosting on It.

When you’re developing web applications, you have to keep
In mind that all the pretty user Interfaces and fancy JavaScript
stuff Is the frosting on the cake. Your website can be really good
without that stuff, and just like a cake, you need a foundation
on which to put your frosting.

I’ve met some people who don’t like frosting. They scrape It
off the cake. I’ve also met people who use web applications
without JavaScript for varying reasons.

Bake these people a really awesome cake. Then add frosting.

Internet Explorer

Internet Explorer currently has the largest user base, and versions 8 and below have very weak HTML5 and CSS3 support. IE 9 improves thissituation, but it’s not widely used yet. That doesn’t mean we can’t use HTML5 and CSS3 in our sites anyway. We can make our sites work in Internet Explorer, but they don’t have to work the same as the versions we develop for Chrome and Firefox. We’ll just provide fallback solutions Asoc wcee sdsoibni’lti tayn ger users and lose customers.


Our users must be able to interact with our websites, whether they are visually impaired, hearing impaired, on older browsers, on slow connections, or on mobile devices. HTML5 introduces some new elements, such as audio, video, and canvas. Audio and video have always had accessibility issues, but the canvas element presents new challenges. The canvas element lets us create vector images within the HTML document using JavaScript. This creates issues for the visually impaired but also causes problems for the 5 percent of web users who have disabled JavaScript.

We need to be mindful of accessibility when we push ahead with new technologies and provide suitable fallbacks for these HTML5 elements, just like we would for people using Internet Explorer.

Deprecated Tags

HTML5 has introduced a lot of new elements, but the specification also deprecates quite a few common elements that you might find in your web pages.4 You’ll want to remove those moving forward.

First, several presentational elements are gone. If you find these in your code, get rid of them! Replace them with semantically correct elements and use CSS to make them look nice.

• basefont
• big
• center
• font
• s
• strike
• tt
• u

Some of those tags are pretty obscure, but you will find a lot of pages out there maintained with visual editors such as Dreamweaver that still contain a lot of font and center tags.

Aside from the presentational elements, support for frames has been removed. Frames have always been popular in enterprise web applications such as PeopleSoft, Microsoft Outlook Web Access, and even custom-built portals. Despite the widespread use, frames caused so many usability and accessibility issues that they just had to go. That means these elements are gone:

• frame
• frameset
• noframes

You should be looking at ways to lay out your interfaces without frames, using regular CSS or some JavaScript. If you’re using frames to ensure the same header, footer, and navigation appears on each page of your application, you should be able to accomplish the same thing with the tools provided by your web development framework. A few other elements are gone because there are better options available:

• acronym gets replaced by abbr.
• applet gets replaced by object.
• dir gets replaced by ul.

In addition to deprecated elements, there are many attributes that are no longer valid. These include presentational attributes such as the following:

• align
• link, vlink, alink, and text attributes on the body tag
• bgcolor
• height and width
• scrolling on the ¡frame element
• valign
• hspace and vspace
• cellpadding, cellspacing, and border on table

If you use target on your links, like this:

<a href=”” target=”_b1ank”>

you’ll want to look at using JavaScript instead, because target is deprecated.

The profile attribute on the head tag is no longer supported either, and this is something you tend to see in a lot of WordPress templates.

Finally, the longdesc attribute for img and ¡frame elements is gone, which is a bit of a disappointment to accessibility advocates, because longdesc was an accepted way of providing additional descriptive information to users of screen readers.

If you plan on using HTML5 with your existing sites, you’ll want to look for these elements and remove them or replace them with more semantic ones. Be sure to validate your pages with the W3C Validator service,5 because this will help you locate deprecated tags and attributes.

Competing Corporate Interests

Internet Explorer is not the only browser slowing adoption of HTML5 and CSS3. Google, Apple, and the Mozilla Foundation have their own agendas as well, and they’re battling it out for supremacy. They’re arguing over video and audio codec support, and they’re including their opinions in their browser releases. For example, Safari will play MP3 audio with the audio element, but ogg files won’t work. Firefox, however, supports ogg files instead of mp3 files.

Eventually these differences will be resolved. In the meantime, we can make smart choices about what we support either by limiting what we implement to the browsers used by our target audiences or by implementing things multiple times, once for each browser until the standards are finalized. It’s not as painful as it sounds.

HTML5 and CSS3 Are Still Works in Progress

They’re not final specifications, and that means anything in those specifications could change. While Firefox, Chrome, and Safari have strong HTML5 support, if the specification changes, the browsers will change with it, and this could lead to some deprecated, broken websites. During the course of writing this book, CSS3 box shadows have been removed and re-added to the specification, and the Web Sockets protocol has been modified, breaking client-server communications entirely.

If you follow the progress of HTML5 and CSS3 and stay up-to-date with what’s happening, you’ll be fine. A good portion of the things we’ll be discussing in this book are going to work for a long time.

When you come across something that doesn’t work in one of your target browsers, you just fill in the gaps as you go, using JavaScript and Flash as your putty. You’ll build solid solutions that work for all our users, and as time goes on, you’ll be able to remove the JavaScript and other fallback solutions without changing your implementations.

But before you think too much about the future, let’s start working with HTML5. There are a bunch of new structural tags waiting to meet you over in the next chapter. So, let’s not keep them waiting, shall we?

Backward Compatibility

One of the best reasons for you to embrace HTML5 today is that it works in most existing browsers. Right now, even in Internet Explorer 6, you can start using HTML5 and slowly transition your markup. It’ll even validate with the W3C’s validation service (conditionally, of course, because the standards are still evolving).

If you’ve worked with HTML or XML, you’ve come across the doctype declaration before. It’s used to tell validators and editors what tags and attributes you can use and how the document should be formed. It’s
also used by a lot of web browsers to determine how the browser will render the page. A valid doctype often causes browsers to render pages in “standards mode.”

Compared to the rather verbose XHTML 1.0 Transitional doctype used by many sites:

the HTML5 doctype is ridiculously simple:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

Place that at the top of the document, and you’re using HTML5.

Down! oad html5_why/index.html
<!DOCTYPE html>

Of course, you can’t use any of the new HTML5 elements that your target browsers don’t yet support, but your document will validate as HTML5.

A Platform for Web Development

A lot of the new features of HTML center around creating a better platform for web-based applications. From more descriptive tags and better cross-site and cross-window communication to animations and improved multimedia support, developers using HTML5 have a lot of new tools to build better user experiences.

More Descriptive Markup
Each version of HTML introduces some new markup, but never before have there been so many new additions that directly relate to describing content. You’ll learn about elements for defining headings, footers, navigation sections, sidebars, and articles in Chapter 2, New Structural Tags and Attributes, on page 24. You’ll also learn about meters, progress bars, and how custom data attributes can help you mark up data.

Multimedia with Less Reliance on Plug-ins
You don’t need Flash or SUverlight for video, audio, and vector graphics anymore. Although Flash-based video players are relatively simple to use, they don’t work on Apple’s mobile devices. That’s a significant
market, so you’ll need to learn how to use non-Flash video alternatives.

Better Applications
Developers have tried all kinds of things to make richer, more interactive applications on the Web, from ActiveX controls to Flash. HTML5 offers amazing features that, in some cases, completely eliminate the
need for third-party technologies.

Cross-Document Messaging
Web browsers prevent us from using scripts on one domain to affect or interact with scripts on another domain. This restriction keeps end users safe from cross-site scripting, which has been used to do all sorts
of nasty things to unsuspecting site visitors.

However, this prevents all scripts from working, even when we write them ourselves and know we can trust the content. HTML5 includes a workaround that is both safe and simple to implement.

Web Sockets
HTML5 offers support for Web Sockets, which give you a persistent connection to a server. Instead of constantly polling a back end for progress updates, your web page can subscribe to a socket, and the back end can push notifications to your users.

Client-Side Storage

We tend to think of HTML5 as a web technology, but with the addition of the Web Storage and Web SQL Database APIs, we can build applications in the browser that can persist data entirely on the client’s machine.

Better Interfaces
The user interface is such an important part of web applications, and we jump through hoops every day to make browsers do what we want. To style a table or round corners, we either use JavaScript libraries or add tons of additional markup so we can apply styles. HTML5 and CSS3 make that practice a thing of the past.

Better Forms
HTML5 promises better user interface controls. For ages, we’ve been forced to use JavaScript and CSS to construct sliders, calendar date pickers, and color pickers. These are all defined as real elements in HTML5, just like drop-downs, checkboxes, and radio buttons. Although this isn’t quite ready yet for every browser,
it’s something you need to keep your eye on, especially if you develop web-based applications. In addition to improved usability without reliance on JavaScript libraries, there’s another benefit—improved accessibility.
Screen readers and other browsers can implement these controls in specific ways so that they work easily for the disabled.

Improved Accessibility
Using the new HTML5 elements in HTML5 to clearly describe our content makes it easier for programs like screen readers to easily consume the content. A site’s navigation, for example, is much easier to find if
you can look for the nav tag instead of a specific div or unordered list. Footers, sidebars, and other content can be easily reordered or skipped altogether. Parsing pages in general becomes much less painful, which
can lead to better experiences for people relying on assistive technologies. In addition, new attributes on elements can specify the roles of elements so that screen readers can work with them easier.

Advanced Selectors
CSS3 has selectors that let you identify odd and even rows of tables, all selected check boxes, or even the last paragraph in a group. You can accomplish more with less code and less markup.

Visual Effects
Drop shadows on text and Images help bring depth to a web page, and gradients can also add dimension. CSS3 lets you add shadows and gradients to elements without resorting to background images or extra markup. In addition, you can use transformations to round corners or skew and rotate elements.

An Overview nf HTMlii and CSS3

HTML5 and CSS3 are more than just two new standards proposed by the World Wide Web Consortium (W3C) and its working groups. They are the next iteration of technologies you use every day, and they’re here to help you build better modern web applications. Before we dive into the deep details of HTML5 and CSS3, let’s talk about some benefits of HTML5 and CSS3, as well as some of the challenges we’ll face.

How This Works

Each chapter in this book focuses on a specific group of problems that we can solve with HTML5 and CSS3. Each chapter has an overview and a table summarizing the tags, features, or concepts covered in the chapter. The main content of each chapter is broken apart into “tips,” which introduce you to a specific concept and walk you through building a simple example using the concept. The chapters in this book are grouped topically. Rather than group things into an HTML5 part and a CSS3 part, it made more sense to group them based on the problems they solve.

Each tip contains a section called “Falling Back,” which shows you methods for addressing the users who use browsers that don’t offer HTML5 and CSS3 support. We’ll be using a variety of techniques to make these fallbacks work, from third-party libraries to our own jQuery plug-ins. These tips can be read in any order you like.

Finally, each chapter wraps up with a section called “The Future,” where we discuss how the concept can be applied as it becomes more widely adopted.

We’ll start off with a brief overview of HTML5 and CSS3 and take a look at some of the new structural tags you can use to describe your page content. Then we’ll work with forms, and you’ll get a chance to use some
of the form fields and features such as autofocus and placeholders. From there, you’ll get to play with CSS3’s new selectors so you can learn how to apply styles to elements without adding extra markup to your content.

Then we’ll explore HTML’s audio and video support, and you’ll learn how to use the canvas to draw shapes. You’ll also get to see how to use CSS3’s shadows, gradients, and transformations, as well as how to learn how to work with fonts.

In the last section, we’ll use HTML5’s client-side features such as Web Storage, Web SQL Databases, and offline support to build client-side applications. We’ll use Web Sockets to talk to a simple chat service, and you’ll see how HTML5 makes it possible to send messages and data across domains. You’ll also get a chance to play with the Geolocation API and learn how to manipulate the browser’s history. We’ll then wrap up by taking a look at a few things that aren’t immediately useful but will become important in the near future.