Richard Clark – HTML5 Doctor http://html5doctor.com helping you implement HTML5 today Tue, 21 Jun 2016 09:50:49 +0000 en-US hourly 1 The main element https://stevefaulkner.github.io/html5doctored/the-main-element/ https://stevefaulkner.github.io/html5doctored/the-main-element/#comments Wed, 26 Jun 2013 08:33:59 +0000 http://html5doctor.com/?p=5081 Recently, main was formally added to the W3C HTML specification. Now that the dust has settled, it's about time we dive in to find out where and when it's appropriate to use main. Let's get started.

]]>
Recently, <main> was formally added to the W3C HTML specification. Now that the dust has settled, it’s about time we dive in to find out where and when it’s appropriate to use <main>. Let’s get started.

History

The inclusion of a main element (or similar) has long been debated in the working groups with authors and others often questioning why we had new elements such as <header>, <article>, and <footer> but no element to accurately describe the primary content of a page.

Steve Faulkner, an accessibility consultant and new doctor in residence, undertook the hard graft of carrying out research, gathering data and use cases, and speaking to implementers to get them interested. As Steve explains, he talked to:

as many implementers (both general browser implementers and accessibility implementers), developers, authors and users as I could and got advice and input from them. I went where the various people hung out; on IRC, mailing lists, twitter, blogs, conferences — anywhere.

This led to his writing an extension specification for <main> and a thorough use case rationale.

The proposal was accepted in November 2012, and <main> was then rolled into the HTML5.1 specification. Recently, it was added to the HTML5 specification following no objections. Lets have a look at how the spec describes <main>.

W3C Specification

The primary purpose of <main> is to map ARIA’s landmark role main to an element in HTML. This will help screen readers and other assistive technologies understand where the main content begins. The W3C spec describes <main> as representing:

The main content of the body of a document or application. The main content area consists of content that is directly related to or expands upon the central topic of a document or central functionality of an application.

Since the <main> element is now included in the HTML specification, the <body> element has reverted to its HTML4 definition:

The body element represents the content of the document.

More Details

One important facet of <main> is that it can only be used once per page. Jeremy Keith wrote to the working group to understand why this is the case (rather than allowing multiple <main>s). Although I won’t go into detail, the discussion is an interesting read.

As per the spec, the W3C validator throws an error if you attempt to use multiple <main> elements per document.

Another stipulation of <main> is that it can’t be used as a descendant of an <article>, <aside>, <footer>, <header>, or <nav> element.

Because <main> isn’t sectioning content, it doesn’t affect the document outline in the same way <article>, <nav>, or <section> do.

Getting Going

Just as with the introduction of many other new HTML5 elements, not all browsers recognise <main> or have preset styles for it. You’ll need to ensure it displays as a block level element in your CSS:

main {display:block;}

For the time being, you'll also need to use JavaScript to create the element for older versions of IE:

<script>document.createElement('main');</script>

Of course, if you use the html5shiv, <main> is now baked in directly.

Implementing <main> on HTML5 Doctor

The easiest way to implement <main> is to replace that <div> that you've likely got with an id or class of something like main or content.

So what does that look like in practice? Well, here's our pre-<main> markup on HTML5 Doctor:

<body>
<header role="banner">
[...]
</header>

<div id="content" class="group" role="main">
[...]
</div>

<footer role="contentinfo">
    [...]
</footer>
</body>

And here's what it's like now:

<body>
<header role="banner">
[...]
</header>

<main id="content" class="group" role="main">
[...]
</main>

<footer role="contentinfo">
    [...]
</footer>
</body>

Yes, it's really that simple. With any luck, it'll take you less than five minutes to implement.

The WHATWG Version

The WHATWG definition of <main> differs from the W3C version in that the element has no meaning. It's merely a styling hook (like a <div> with a new name) and represents its children.

The main element can be used as a container for the dominant contents of another element. It represents its children.

We recommend using the W3C version of <main> as described above.

Browser Support

Firefox 21, Chrome 26, and a WebKit r140374 have all implemented basic support for <main>.

They have all mapped the ARIA role="main" to the <main> element so assistive technologies can now recognise the <main> element without issue.

Summary

As you've seen, it's super easy to get up and running with <main>. It only takes a few minutes, so now really is the time to start adding it to the sites you're developing.

If you aren't sure when or where to use <main>, be sure to ask us in the comments and one of us will try to help you out.

Further reading

The main element originally appeared on HTML5 Doctor on June 26, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/the-main-element/feed/ 106
HTML5 forms input types https://stevefaulkner.github.io/html5doctored/html5-forms-input-types/ https://stevefaulkner.github.io/html5doctored/html5-forms-input-types/#comments Thu, 28 Feb 2013 14:00:01 +0000 http://html5doctor.com/?p=4993 In the first article in this series we looked at the history of HTML5 forms and many of the new attributes available to us. In this second and final part of the series, we'll look at the new input types available in HTML5. As we'll see, these new features will go a long way toward making your life easier while delivering a delightful user experience. The best thing about all this? You can start using them now.

]]>
In the first article in this series we looked at the history of HTML5 forms and many of the new attributes available to us. In this second and final part of the series, we’ll look at the new input types available in HTML5. As we’ll see, these new features will go a long way toward making your life easier while delivering a delightful user experience. The best thing about all this? You can start using them now.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

Note: As this article is a book excerpt, browser renderings of attributes and input types may have altered since the screenshots were taken. Additionally, browser support may have increased since publication so please refer to the links at the end of the article for the current state of browser support.

New input types

HTML5 introduces no less than a baker’s dozen (yes, that’s 13!) new input types for forms. We’re going to take a brief look at each of them and explain why you should be using them right now. These new input types have dual benefits: using them means less development time and an improved user experience. The new input types we’ll be looking at are:

email

In rendering terms, the email input type is no different than a standard text input type and allows for one or more e-mail addresses to be entered. Combined with the required attribute, the browser is then able to look for patterns to ensure a valid e-mail address has been entered. Naturally, this checking is rudimentary, perhaps looking for an @ character or a period (.) and not allowing spaces. Opera 9.5+, Firefox 4+, Internet Explorer 10 and Chrome 5+ have already implemented this basic validation. The browser goes as far as presenting the user with an error message (see Opera in Figure 3) if the e-mail address entered isn’t valid. You can style the field for when an value is entered using the :valid, :invalid or :required pseudo class (assuming you have the required attribute on the input) just like Locum Dr. Peter explained.

<input type="email" name="email" required>
Screenshot of an email input field in Opera with an error message stating 'Please enter a valid email address' with 'gordo' written in the field
Figure 3. Opera e-mail address error messaging

The specification details that one or more e-mail addresses are allowed. This means that the multiple attribute could be used with type="email" too.

Pretty cool, huh? Again, this highlights how HTML5 forms help to cut down the amount of JavaScript that you have to write when carrying out form validation.

There’s always a catch, though, right? At the time of writing, there is an internationalization issue with type="email". When using it with double-byte internationalized domain names, the browsers invalidate them; so this example

<input type="email" name="email" value="gordo@日本.jp">

isn’t valid in Firefox, Safari, or Chrome (there is no issue in Opera). However, a workaround has been created by Kyle Barrow that uses type="text" with the pattern attribute, as shown here:

<input type="text" name="email" value="gordo@日本.jp" pattern="[^ @]*@[^ @]*">

An alternative solution is to continue using type="email" with the formnovalidate attribute on the submit button, as follows. This ensures that no validation will be carried out on form submission, which may or may not be suitable for your needs.

<form action="process.php">
<label for="email">Email:</label>
<input type="email" name="email" value="gordo@日本.jp">
<input type="submit" formnovalidate value="Submit">
Or you could use the novalidate attribute on your form, like so:

<form action="process.php" novalidate> <label for="email">Email:</label>
<input type="email" name="email" value="gordo@日本.jp">
<input type="submit" value="Submit">

Internationalization issues aside, remember how we said there are dual benefits to HTML5’s input types—less development time and better user experience? Let’s go back and look at the iPhone once more, as shown in Figure 4.

Screenshot of an iPhone with dynamic keyboard and the action button saying 'Go' when focussed on the email input field
Figure 4. The iPhone displays a custom keyboard when using type=”email”.

Did you notice it this time? No? Look at the keyboard again. That’s right, the keyboard is different. There are dedicated keys for the @ and . characters to help you complete the field more efficiently. As we discussed with type="search", there is no downside to using type="email" right now. If a browser doesn’t support it, it will degrade to type="text". And in some browsers, users will get a helping hand.

url

The url input type, as you might expect, is for web addresses. You can use the multiple attribute to enter more than one URL. Like type="email", a browser will carry out simple validation on these fields and present an error message on form submission. This is likely to include looking for forward slashes, periods, and spaces, and possibly detecting a valid top-level domain (such as .com or .co.uk). Use the url input type like so:

<input type="url" name="url" required>

Again, we’ll take a look at how the iPhone renders type="url". As you can see in Figure 5, it has again updated the onscreen keyboard to ensure that completing the field is as simple as possible for the user by swapping the default space key for period, forward slash, and .com keys. (To access more endings like .org and .net, tap and hold the .com key.)

Screenshot of an iPhone with dynamic keyboard and the action button saying 'Go' when focussed on the URL input field
Figure 5. type=”url” activates a URL-specific keyboard on the iPhone.

tel

tel differs from email and url in that no particular syntax is enforced. Phone numbers differ around the world, making it difficult to guarantee any type of specific notation except for allowing only numbers and perhaps a + symbol to be entered. It’s possible that you can validate specific phone numbers (if you can guarantee the format) using client-side validation. type="tel" is marked up as follows:

<input type="tel" name="tel" id="tel" required>

Once more, the iPhone recognises type="tel", only this time it goes one step further and completely changes the keyboard to the standard phone keyboard, as shown on the left in Figure 6. In addition to the iPhone, some Android devices (such as HTC Desire, shown on the right in Figure 6) also display a numeric keyboard for type="tel". That’s pretty handy, don’t you think? Nice, big keys for entering a phone number help you to get that big, nasty form completed quickly.

Screenshot of an iPhone and Android device with dynamic keyboard changing to a number input when the user is focussed on a tel input field
Figure 6. type="tel" on the iPhone and some Android devices dynamically changes the keyboard to a numeric keypad. (Android screenshot provided by Stuart Langridge).

number

number, as you might expect, is used for specifying a numerical value. As with the majority of these new input types, Opera was the first to implement type="number". It, Safari, and Chrome render the input as a spinbox control (see Figure 7) whereby you can click the arrows to move up or down. Or if you prefer, you can type directly into the field. Firefox, on the other hand, renders the field like a standard text box. Support for type=”number” is in IE 10 also, although if you enter a non-numerical character the field empties when focus is lost and no feedback is provided to the user.

Screenshot of the Opera browser rendering of a number input field for 'showe size' the value is 9 and there are up and down arrows to the right of the field.
Figure 7. type="number" in Opera

With the additional attributes min, max, and step we can change the default step value of this spinbox control as well as set minimum, maximum, and starting values (using the standard HTML value attribute). This example shows how these attributes work:

<input type="number" min="5" max="18" step="0.5" value="9" name="shoe-size">

In this example, min represents the minimum value the field will accept, and max represents the maximum value. If we reach the maximum or minimum value, the appropriate arrow on the spinbox control will be greyed out so you can no longer interact with it. step is the increment that the value should adjust up or down, with the default step value being 1. This means we can include negative values or step up in increments of 0.5 or 5. value is that attribute you’re used to from previous versions of HTML. Each of the attributes are optional, with defaults being set if they aren’t used.

In contrast to Opera’s implementation, the iPhone (Figure 8) and some Android devices (such as HTC Desire, shown on the right in Figure 6-13) simply render the field as a standard text box but optimize the keyboard for easy input.

Screenshot of an iPhone and Android device with dynamic keyboard changing to a number input when the user is focussed on a number input field
Figure 8. type="number" on iPhone and Android HTC Desire (Android screenshot provided by Stuart Langridge)

To make the iPhone render with the standard telephone keypad as we saw for type="text" Chris Coyier, of CSS Tricks devised a little hoax you can use. Rather than using type=”number”, use a standard type="text" input and add a pattern attribute that accepts only numbers, as shown below. This solution isn’t ideal but if you think it could be useful, Chris has put a short video together showing it in action.

<input type="text" pattern="[0-9]*" name="shoe-size">

Chris’ technique may soon become absolete though with the introduction of the inputmode attribute. The attribute, recently added to the specification will allow users to specify the type of input mechanism that is most useful for users. When implemented, you will be able to choose between numeric, latin, email, or kana input modes.

range

The range input type is similar to number but more specific. It represents a numerical value within a given range. Why the difference, I hear you cry? Because when you’re using range, the exact value isn’t important. It also allows browsers to offer a simpler control than for number. In Opera, Safari, Internet Explorer 10 and Chrome, type="range" renders as a slider (see Figure 6-14). When moving the slider in IE 10 a tooltip appears showing the current value. Additionally, in Opera, if the CSS defines the height greater than the width, the slider control will be rendered vertically as opposed to the standard horizontal rendering.

The following code shows how we might mark up our skill level on a scale of 1 to 100 by setting the min and max attributes (see Figure 9). We can also set the starting point for range using the value attribute.

<input id="skill" type="range" min="1" max="100" value="0">
Screenshot of the range input type for Flying Skill level as rendered by Opera.
Figure 9. type="range" in Chrome

Dates and times

If you’ve ever booked tickets online, you will have come across date pickers to help you quickly and easily choose the date you require. Perhaps you’ve even implemented a date picker on your own website. Generally, this is done using a JavaScript library such as jQuery, Dojo, or YUI. It can be a pain when you need to load a whole library and associated plug-ins just to implement a simple date picker. Well, with HTML5 we get that functionality baked into the browser. Not only that, but we don’t have to stop at just electing a single date; we can select a week, month, time, date and time, and even date and time with a time zone using the different input types. The markup is pretty straightforward.

<input id="dob" name="dob" type="date">

You can go a step further by using the min and max attributes to ensure the user can only choose from a specified date range.

<input id="startdate" name="startdate" min="2012-01-01" max="2013-01-01" type="date">

As with many of the other form implementations, Opera leads the way (support in other browsers is varied). Let’s take a look next at how browsers render these input types.

date

Figure 10 shows Opera 10.5’s rendering of type="date".

Screenshot of the date input type rendered by Opera. There is a dropdown for the date and a calendar widget shown.
Figure 10. type="date" in Opera 10.5

These date pickers aren’t restricted to desktop devices; some Blackberry devices and Chrome for Android render its internal date picker when used with type="date" (see Figure 11).

Screenshot of the date input type as rendered on a Blackberry. There are three spinners, one for day, one for month and another for year.
Figure 11. type="date" on Blackberry (screenshot provided by Terence Eden)

month

Next up, Figure 12 shows type="month", which might, for example, be used for a credit card expiry date.

<input id="expiry" name="expiry" type="month" required>
Screenshot of the month input type rendered by Opera. There is a dropdown for the date and a calendar widget shown with the current month highlighted.
Figure 12. type="month" in Opera 10.5

week

You can also drill down to type="week". Notice how Opera highlights a specific week using the same date picker control, as shown in Figure 13.

<input id="vacation" name="vacation" type="week">
Screenshot of the week input type rendered by Opera. There is a dropdown for the date and a calendar widget shown with the current week highlighted.
Figure 13. type="week" in Opera 10.5

time

You can see in Figure 14 that type="time" renders a spinbox similar to that used earlier for selecting the precise time.

<input id="exit-time" name="exit-time" type="time">
Screenshot of the time input type rendered by Opera. There is an input with a value of 14:10 and up and down arrows to the right of the input.
Figure 14. type="time" in Opera 10.5

datetime

We can combine the date and time by using type="datetime" for specifying a precise time on a given day, as shown in Figure 15.

<input id="entry-day-time" name="entry-day-time" type="datetime">
Screenshot of the datetime input type rendered by Opera. There is a dropdown for the date and a calendar widget shown with the current day highlighted. There is an input with a value of 12:08 and up and down arrows to the right of the input along with the text 'UTC'.
Figure 15. type="datetime" in Opera 10.5

datetime-local

Finally, Figure 16 shows that we can achieve slightly more granular control by selecting a precise time on a given day with a local time zone variation using type="datetime-local".

<input id="arrival-time" name="arrival-time " type="datetime-local">
Screenshot of the datetime-local input type rendered by Opera. There is a dropdown for the date and a calendar widget shown with the current day highlighted. There is an input with a value of 17:08 and up and down arrows to the right.
Figure 16. type="datetime-local" in Opera 10.5

Date and time caveats

There are two caveats with these implementations. First, with the current implementation, it isn’t possible to type a date into the field (in all browsers). The date picker is keyboard accessible, though. However, we can foresee a potential issue; if implemented on a form that a data entry clerk regularly completes, they are likely to be quicker at typing the date than tabbing through with the keyboard or selecting from a date picker. Second, it isn’t possible to style the look of the date picker. We tend to think that this is a good thing, as users will receive a common experience across all websites they visit (provided they use the same browser all the time). Undoubtedly, though, corporations will require a branded date picker. Safari 5 and Chrome 5 have implemented these input types, but, unfortunately, they aren’t very user friendly. Dates have to be entered in the same format as the time element that we met earlier in the book. So for dates, the format would be YYYY-MM-DD, and for dates with time, a user would have to enter YYYYMM-DDT00:00Z, which is not very friendly at all.

As with the other new input types, if a browser doesn’t recognize them, it will simply default back to type="text" and let the user continue to use your JavaScript date picker.

color

The color input type is pretty self-explanatory: it allows the user to select a color and returns the hex value for that color. It is anticipated that users will either be able to type the value or select from a color picker, which will either be native to the operating system or a browser’s own implementation. Opera 11 has implemented type=”color” with a simple color picker that offers a number of standard color choices or the option to select Other, which brings up the operating system color picker (shown on the right in Figure 17).

<input id="color" name="color" type="color">
Screenshot of the color input type as rendered by Opera. There is a colour dropdown which when clicked shows a range of colours with an 'other' button. The right shows the dialog box opened when the user clicks 'Other' which is a standard operating system color dialog.
Figure 17. type="color" in Opera on the left and the result of clicking Other shown on the right

In contrast, certain Blackberry devices have implemented the color input type that renders a color picker, as shown in Figure 18.

Screenshot of the color input type as rendered on a Blackberry. There is a colour spectrum with a hue box and a color preview alongside an 'OK' button.
Figure 18. type="color" on Blackberry (screenshot provided by Terence Eden)

Input types summary

By using HTML5’s new form input types right now, we can enhance the user’s experience, future-proof our site, and make our life as developers easier. Obviously, we can’t just leave the browsers that don’t support all these new features hanging, and in Chapter 6 of Beginning HTML5 and CSS3 we take a look at how to detect support for these form features using JavaScript.

You can find a dummy form, using some of the examples we’ve shown in this article at our HTML5 forms demo page.

We’ve hinted throughout the article at which browsers have support for HTML5 forms input types and attributes. With new versions of browsers being released at an ever-increasing rate, it can be difficult to keep up with what is or isn’t supported. If you want to keep an eye on the current progress, we suggest visiting When can I use … or FindMeByIP or Wufoo’s HTML5 forms research.

If you missed the first article in this series on HTML5 forms, why not read a brief History of HTML5 forms and learn all about the new attributes introduced.

Cover image of Beginning HTML5 and CSS3: The Web Evolved.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

HTML5 forms input types originally appeared on HTML5 Doctor on February 28, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/html5-forms-input-types/feed/ 21
HTML5 forms introduction and new attributes https://stevefaulkner.github.io/html5doctored/html5-forms-introduction-and-new-attributes/ https://stevefaulkner.github.io/html5doctored/html5-forms-introduction-and-new-attributes/#comments Tue, 26 Feb 2013 14:30:58 +0000 http://html5doctor.com/?p=5001 No doubt you interact with at least one form on the Web every day. Whether you're searching for content or logging in to your e-mail account or Facebook page, using online forms is one of the most common tasks performed on the Web. As designers and developers, creating forms has a certain monotony about it, particularly writing validation scripts for them. HTML5 introduces a number of new attributes, input types, and other elements for your markup toolkit. In this article we'll be focussing on the new attributes with a future article looking at the new input types.

]]>
No doubt you interact with at least one form on the Web every day. Whether you’re searching for content or logging in to your e-mail account or Facebook page, using online forms is one of the most common tasks performed on the Web. As designers and developers, creating forms has a certain monotony about it, particularly writing validation scripts for them. HTML5 introduces a number of new attributes, input types, and other elements for your markup toolkit. In this article we’ll be focussing on the new attributes with a future article looking at the new input types.

As we’ll see, these new features will go a long way toward making your life easier while delivering a delightful user experience. The best thing about all this? You can start using them now. We’ll start with a (very) brief history of HTML5 forms though.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

Note: As this article is a book excerpt, browser renderings of attributes and input types may have altered since the screenshots were taken. Additionally, browser support may have increased since publication so please refer to the links at the end of the article for the current state of browser support.

A history of HTML5 forms

The forms section of HTML5 was originally a specification titled Web Forms 2.0 that added new types of controls for forms. Started by Opera and edited by then-Opera employee Ian Hickson, it was submitted to the W3C in early 2005. The work was initially carried out under the W3C. It was then combined with the Web Applications 1.0 specification to create the basis of the breakaway Web Hypertext Application Technology Working Group (WHATWG) HTML5 specification.

Using HTML5 design principles

One of the best things about HTML5 forms is that you can use almost all of these new input types and attributes right now. They don’t even need any shivs, hacks, or workarounds. That isn’t to say they’re all “supported” right now, but they do cool things in modern browsers that do support them-and degrade gracefully in browsers that don’t understand them. This is thanks to HTML5’s design principles. In this instance we’re specifically referring to the principle of graceful degradation. In essence, this means that there’s no excuse for not using these features right now. In fact, it means you’re ahead of the curve.

HTML5 form attributes

There are 14 new attributes that we’ll be looking at in this article.

placeholder

First up is the placeholder attribute, which allows us to set placeholder text as we would currently do in HTML4 with the value attribute. It should only be used for short descriptions. For anything longer, use the title attribute. The difference from HTML4 is that the text is only displayed when the field is empty and hasn’t received focus. Once the field receives focus (e.g., you click or tab to the field), and you begin to type, the text simply disappears. It’s very similar to the search box you see in Safari (see Figure 1).

Screenshot of the browser search box in Safari with and without focus
Figure 1. Browser search box in Safari without and with focus

Let’s have a look at how to implement the placeholder attribute.

<input type="text" name="user-name" id="user-name" placeholder="at least 3 characters">

That’s it! We can hear you thinking, “What’s so great about that? I’ve been doing it with JavaScript for years.” Yes, that’s true. However, with HTML5, it’s part of the browser, meaning less scripting is required for a more accessible, cross-browser solution (even when JavaScript is disabled). Figure 2 shows the placeholder attribute working in Chrome.

Screenshot of an input field in Chrome with and without focus, so showing and not showing the placeholder
Figure 2. Placeholder attribute support in Chrome, unfocused and focused

Browsers that don’t support the placeholder attribute ignore it, so it won’t render. By including it, though, you’re providing an enhanced user experience for those users who have browser support and you’re “future proofing” your site. All modern browsers support placeholder.

Note: There is no official pseudo-class for styling placeholder text but both Mozilla (makers of Firefox) and WebKit offer vendor prefixed properties for styling (-mozplaceholder and –webkit-input-placeholder). This makes it safe to assume that a pseudo-class will become standard for styling placeholder text. For further detail there is a thread on the WHATWG mailing list about this topic.

autofocus

autofocus does exactly what it says on the tin. Adding it to an input automatically focuses that field when the page is rendered. As with placeholder, autofocus is something that we used JavaScript for in the past.

Traditional JavaScript methods do, though, have some serious usability problems. For example, if a user begins completing the form before the script loads, they will (jarringly) be returned to the first form field when the script is loaded. The autofocus attribute in HTML5 gets around this issue by focusing as soon as the document loads, without having to wait for the JavaScript to be loaded. However, we only recommend using it for pages whose sole purpose is the form (like Google) to prevent the usability issues.

It is a Boolean attribute (except if you are writing XHTML5; see the note) and is implemented as follows:

<input type="text" name="first-name" id="first-name" autofocus>

All modern browsers support the attribute and, like placeholder, browsers that don’t support the autofocus attribute simply ignore it.

Note: Several new HTML5 form attributes are Boolean attributes. This just means they’re set if they’re present and not set if they’re absent. They can be written several ways in HTML5.

autofocus
autofocus=""
autofocus="autofocus"

However, if you are writing XHTML5, you have to use the autofocus="autofocus" style.

autocomplete

The autocomplete attribute helps users complete forms based on earlier input. The attribute has been around since IE5.5 but has finally been standardized as part of HTML5. The default state is set to on. This means that generally we won’t have to use it. However, if you want to insist that a form field be entered each time a form is completed (as opposed to the browser autofilling the field), you would implement it like so:

<input type="text" name="tracking-code" id="tracking-code" autocomplete="off">

The autocomplete state on a field overrides any autocomplete state set on the containing form element.

required

The required attribute doesn’t need much introduction; like autofocus, it does exactly what you’d expect. By adding it to a form field, the browser requires the user to enter data into that field before submitting the form. This replaces the basic form validation currently implemented with JavaScript, making things a little more usable and saving us a little more development time. required is a Boolean attribute, like autofocus. Let’s see it in action.

<input type="text" id="given-name" name="given-name" required>

required is currently implemented only in Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+, so for the time being you need to continue writing a script to check that fields are completed on the client side in other browsers (*cough* IE!). Opera, Chrome, and Firefox show the user an error message (see Figure 3) upon form submission. In most browsers, the errors are then localized based on the declared language. Safari doesn’t show an error message on submit, but instead places focus on that field.

Screenshot from Opera showing an error message on an input field
Figure 3. Form field with required attribute displaying a browser-generated error message in Opera

The default rendering of “required” error messages depends on the individual browser; at present the error message bubble can’t be styled with CSS in all browsers. Chrome, however, does have a proprietary property that you can use to style the error bubble. Peter Gasston has written an article about the syntax. You can also style the input using the :required pseudo-class. An alternative is to override the wording and styling using the setCustomValidity() method in JavaScript. Importantly, don’t forget that this browser validation is no substitute for validating on the server as well.

pattern

The pattern attribute is likely to get a lot of developers very excited (well, as excited as you can get about form attributes). It specifies a JavaScript regular expression for the field’s value to be checked against. pattern makes it easy for us to implement specific validation for product codes, invoice numbers, and so on. The possibilities for pattern are wide-ranging, and this is just one simple example using a product number.

<label>Product Number:
<input pattern="[0-9][A-Z]{3}" name="product" type="text" title="Single digit followed by three uppercase letters."/>
</label>

This pattern prescribes that the product number should be a single digit [0-9] followed by three uppercase letters [A-Z]{3}. For more examples, the HTML5 Pattern website lists common regex style patterns to help get you started.

As with required, Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+ are the only browsers with support for pattern at present. However, with the browser market moving at a fast pace, the others will soon catch up.

list and the datalist element

The list attribute enables the user to associate a list of options with a particular field. The value of the list attribute must be the same as the ID of a datalist element that resides in the same document. The datalist element is new in HTML5 and represents a predefined list of options for form controls. It works in a similar way to the in-browser search boxes that autocomplete as you type (see Figure 4).

Screenshot Google's autosuggest functionality in Safaris search box
Figure 4. Google search autosuggestions in Safari

The following example shows how list and datalist are combined (see Figure 5):

<label>Your favorite fruit:
<datalist id="fruits">
  <option value="Blackberry">Blackberry</option>
  <option value="Blackcurrant">Blackcurrant</option>
  <option value="Blueberry">Blueberry</option>
  <!-- … -->
</datalist>
If other, please specify:
  <input type="text" name="fruit" list="fruits">
</label>

By adding a select element inside the datalist you can provide superior graceful degradation than by simply using an option element. This is an elegant markup pattern designed by Jeremy Keith that adheres perfectly with HTML5’s principle of degrading gracefully.

<label>Your favorite fruit:
<datalist id="fruits">
  <select name="fruits">
    <option value="Blackberry">Blackberry</option>
    <option value="Blackcurrant">Blackcurrant</option>
    <option value="Blueberry">Blueberry</option>
    <!-- … -->
  </select>
If other, please specify:
</datalist>
  <input type="text" name="fruit" list="fruits">
</label>

Browser support for list and datalist is currently limited to Opera 9.5+ (see Figure 5), Chrome 20+, Internet Explorer 10 and Firefox 4+.

Screenshot of the list attribute and datalist element in Opera
Figure 5. The datalist element rendered in Opera

multiple

We can take our lists and datalists one step further by applying the Boolean attribute multiple to allow more than one value to be entered from the datalist. Here is an example.

<label>Your favorite fruit:
<datalist id="fruits">
  <select name="fruits">
    <option value="Blackberry">Blackberry</option>
    <option value="Blackcurrant">Blackcurrant</option>
    <option value="Blueberry">Blueberry</option>
    <!-- … -->
  </select>
If other, please specify:
</datalist>
  <input type="text" name="fruit" list="fruits" multiple>
</label>

multiple isn’t exclusively for use with datalists, though. A further example for multiple might be for email addresses when sending items to friend or the attachment of files, as shown here:

<label>Upload files:
<input type="file" multiple name="upload"></label>

multiple is supported in Firefox 3.6+, Safari 4+, Opera 11.5+, Internet Explorer 10 and Chrome 4+.

novalidate and formnovalidate

The novalidate and formnovalidate attributes indicate that the form shouldn’t be validated when submitted. They are both Boolean attributes. formnovalidate can be applied to submit or image input types. The novalidate attribute can be set only on the form element.

An example use case for the formnovalidate attribute could be on a “save draft” button, where the form has fields that are required for submitting the draft but aren’t required for saving the draft. novalidate would be used in cases where you don’t want to validate the form but do want to take advantage of the more useful user interface enhancements that the new input types offer.

The following example shows how to use formnovalidate:

<form action="process.php">
  <label for="email">Email:</label>
  <input type="text" name="email" value="gordo@example.com">
  <input type="submit" formnovalidate value="Submit">
</form>

And this example shows how to use novalidate:

<form action="process.php" novalidate>
  <label for="email">Email:</label>
  <input type="text" name="email" value="gordo@example.com">
  <input type="submit" value="Submit">
</form>

form

The form attribute is used to associate an input, select, or textarea element with a form (known as its form owner). Using form means that the element doesn’t need to be a child of the associated form and can be moved away from it in the source. The primary use case for this is that input buttons that are placed within tables can now be associated with a form.

<input type="button" name="sort-l-h" form="sort">

formaction, formenctype, formmethod, and formtarget

The formaction, formenctype, formmethod, and formtarget attributes each have a corresponding attribute on the form element, which you’ll be familiar with from HTML4, so let’s run through each of them briefly. These new attributes have been introduced primarily because you may require alternative actions for different submit buttons, as opposed to having several forms in a document.

formaction

formaction specifies the file or application that will submit the form. It has the same effect as the action attribute on the form element and can only be used with a submit or image button (type="submit" or type="image"). When the form is submitted, the browser first checks for a formaction attribute; if that isn’t present, it proceeds to look for an action attribute on the form.

<input type="submit" value="Submit" formaction="process.php">

formenctype

formenctype details how the form data is encoded with the POST method type. It has the same effect as the enctype attribute on the form element and can only be used with a submit or image button (type="submit" or type="image"). The default value if not included is application/x-www-formurlencoded.

<input type="submit" value="Submit" formenctype="application/x-www-form-urlencoded">

formmethod

formmethod specifies which HTTP method (GET, POST, PUT, DELETE) will be used to submit the form data. It has the same effect as the method attribute on the form element and can only be used with a submit or image button (type="submit" or type="image").

<input type="submit" value="Submit" formmethod="POST">

formtarget

formtarget specifies the target window for the form results. It has the same effect as the target attribute on the form element and can only be used with a submit or image button (type="submit" or type="image").

<input type="submit" value="Submit" formtarget="_self">

Form attributes summary

We’ve looked at several new form attributes that help improve user experience and save you development time. There are some more new attributes to discuss, which are covered together with HTML5’s new input types in the next article in this series.

You can find a dummy form, using some of the examples we’ve shown in this article at our HTML5 forms demo page.

We’ve hinted throughout the article at which browsers have support for HTML5 forms input types and attributes. With new versions of browsers being released at an ever-increasing rate, it can be difficult to keep up with what is or isn’t supported. If you want to keep an eye on the current progress, we suggest visiting When can I use … or FindMeByIP or Wufoo’s HTML5 forms research.

Cover image of Beginning HTML5 and CSS3: The Web Evolved.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

HTML5 forms introduction and new attributes originally appeared on HTML5 Doctor on February 26, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/html5-forms-introduction-and-new-attributes/feed/ 22
Simplequiz #7: Pinterest https://stevefaulkner.github.io/html5doctored/html5-simplequiz-7-pinterest/ https://stevefaulkner.github.io/html5doctored/html5-simplequiz-7-pinterest/#comments Tue, 22 Jan 2013 15:22:02 +0000 http://html5doctor.com/?p=4776 One of our readers commented on an article a while ago (I won't tell you which one just now ;) asking about marking up items on Pinterest. It struck me that this would be a prime candidate for a Simplequiz, so here we are.

]]>
One of our readers commented on an article a while ago (I won’t tell you which one just now ;) asking about marking up items on Pinterest. It struck me that this would be a prime candidate for a Simplequiz, so here we are.

Pinterest, for the uninitiated of you, allows you to organise and share things you love — mostly food, drink, and kittens.

Pinterest Homepage Screengrab
A distinct lack of kittens on Pinterest’s homepage in this screengrab

We’re going to look at how to mark up a single pinned item, as shown below:

Individual pinned item on PinterestIndividual pinned item on Pinterest
The item we’ll be marking up (bottom image is the hovered state)

The existing markup is below (I’ve simplified it a little to make it easier to read):

<div class="pin">
  <div class="pin-holder">
    <div class="actions">
      <a href="#repin">Repin</a>
      <a href="#like">Like</a>
      <a href="#comment">Comment</a>
    </div>
    <a href="me/cat/">
      <img src="cat.jpg" alt="My awesome cat">
    </a>
  </div>
  <p>Awesome cat description.</p>
  <p class="stats">
    <span>25 likes</span>
    <span>2 comments</span>
    <span>100 repins</span>
  </p>
  <div class="convo">
    <a href="/me/">
      <img src="me.jpg" alt="Profile picture of me">
    </a>
    <p><a href="/me/">Me</a> onto <a href="/here/">here</a></p>
  </div>
</div>

So, all’s well and good, but how should it be marked up in HTML5? As the saying goes, there are a hundred ways to skin a cat (excuse the pun). We’ve created five possible options, one of which achieved some consensus amongst the Doctors. Be warned: some of the differences between options are small and may be difficult to spot. Look carefully at each option!

Let us know which answer you would go with (or roll your own) in the comments. Make sure you show your working out. Also, please escape your HTML (or use pseudo code), or we’ll put a severed unicorn head skinned cat in your bed.

Answer A:

An <article>, with <nav> and <aside> elements:

<article class="pin">
  <div class="pin-holder">
    <nav class="actions">
      <a href="#repin">Repin</a>
      <a href="#like">Like</a>
      <a href="#comment">Comment</a>
    </nav>
    <a href="me/cat/">
      <img src="cat.jpg" alt="My awesome cat">
    </a>
  </div>
  <p>Awesome cat description.</p>
  <aside class="stats">
    <span>25 likes</span>
    <span>2 comments</span>
    <span>100 repins</span>
  </aside>
  <article class="convo">
    <a href="/me/">
      <img src="me.jpg" alt="Profile picture of me">
    </a>
    <p><a href="/me/">Me</a> onto <a href="/here/">here</a></p>
  </article>
</article>

Answer B:

An <article>, with <aside> elements:

<article class="pin">
  <div class="pin-holder">
    <aside class="actions">
      <a href="#repin">Repin</a>
      <a href="#like">Like</a>
      <a href="#comment">Comment</a>
    </aside>
    <a href="me/cat/">
      <img src="cat.jpg" alt="My awesome cat">
    </a>
  </div>
  <p>Awesome cat description.</p>
  <aside class="stats">
    <span>25 likes</span>
    <span>2 comments</span>
    <span>100 repins</span>
  </aside>
  <article class="convo">
    <a href="/me/">
      <img src="me.jpg" alt="Profile picture of me">
    </a>
    <p><a href="/me/">Me</a> onto <a href="/here/">here</a></p>
  </article>
</article>

Answer C:

An <article>, with <nav>, <figure>, and <aside> elements:

<article class="pin">
  <div class="pin-holder">
    <nav class="actions">
      <a href="#repin">Repin</a>
      <a href="#like">Like</a>
      <a href="#comment">Comment</a>
    </nav>
    <figure>
      <a href="me/cat/">
        <img src="cat.jpg" alt="My awesome cat">
        <figcaption>Awesome cat description.</figcaption>
      </a>
    </figure>
  </div>
  <aside class="stats">
    <span>25 likes</span>
    <span>2 comments</span>
    <span>100 repins</span>
  </aside>
  <article class="convo">
    <a href="/me/">
      <img src="me.jpg" alt="Profile picture of me">
    </a>
    <p><a href="/me/">Me</a> onto <a href="/here/">here</a></p>
  </article>
</article>

Answer D:

A <section>, with <aside> and <figure> elements:

<section class="pin">
  <div class="pin-holder">
    <aside class="actions">
      <a href="#repin">Repin</a>
      <a href="#like">Like</a>
      <a href="#comment">Comment</a>
    </aside>
    <figure>
      <a href="me/cat/">
        <img src="cat.jpg" alt="My awesome cat">
        <figcaption>Awesome cat description.</figcaption>
      </a>
    </figure>
  </div>
  <p class="stats">
    <span>25 likes</span>
    <span>2 comments</span>
    <span>100 repins</span>
  </p>
  <div class="convo">
    <a href="/me/">
      <img src="me.jpg" alt="Profile picture of me">
    </a>
    <p><a href="/me/">Me</a> onto <a href="/here/">here</a></p>
  </div>
</section>

Answer E:

A <div>, with child <article> and <aside> elements:

<div class="pin">
  <article class="pin-holder">
    <aside class="actions">
      <a href="#repin">Repin</a>
      <a href="#like">Like</a>
      <a href="#comment">Comment</a>
    </aside>
    <a href="me/cat/">
      <img src="cat.jpg" alt="My awesome cat">
      <p>Awesome cat description.</p>
    </a>
  </article>
  <aside class="stats">
    <span>25 likes</span>
    <span>2 comments</span>
    <span>100 repins</span>
  </aside>
  <div class="convo">
    <a href="/me/">
      <img src="me.jpg" alt="Profile picture of me">
    </a>
    <p><a href="/me/">Me</a> onto <a href="/here/">here</a></p>
  </div>
</div>

Your answers below, please, with your rationale, by Tuesday, 29th January.

Simplequiz #7: Pinterest originally appeared on HTML5 Doctor on January 22, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/html5-simplequiz-7-pinterest/feed/ 64
Your HTML5 Questions 20 https://stevefaulkner.github.io/html5doctored/your-html5-questions-20/ https://stevefaulkner.github.io/html5doctored/your-html5-questions-20/#comments Tue, 09 Oct 2012 14:09:40 +0000 http://html5doctor.com/?p=4762 We're back again to answer some more of your questions. This time we've included a bonus answer so you've got six to go at, rather than the usual 5. In this post cover a XMLHttpRequest query, how to define sections, understanding outlines, what markup to use for a social bar, using HTML5 with a legacy site and hidden headings for accessibility.

]]>
We’re back again to answer some more of your questions. This time we’ve included a bonus answer so you’ve got six to go at, rather than the usual five!

In this post, we’ll cover an XMLHttpRequest query, how to define sections, understanding outlines, which markup to use for a social bar, using HTML5 with a legacy site, and hidden headings for accessibility.

XMLHttpRequest

Kieran asked:

I have a test web page where I read the contents of a text file in my dropbox public folder using XMLHttpRequest. However my code works fine in IE but does not work in firefox. I thought XMLHttpRequest2 would work with HTML5. Can you help? Here is the code:

<!DOCTYPE html><html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>JS file reading</title>
  <!--<link href="layout.css" rel="stylesheet" type="text/css">-->
</head>
<body>
  <script type="text/javascript">
    var oRequest = new XMLHttpRequest();
    var sURL = "http://dl.dropbox.com/u/34358808/test1.pkl";

    oRequest.open("GET",sURL,false);
    oRequest.setRequestHeader("User-Agent",navigator.userAgent);
    oRequest.send(null)

    if (oRequest.status==200) alert(oRequest.responseText);
    else alert("Error executing XMLHttpRequest call!");
  </script>
  Reading files with javascript
</body>
</html>

I wouldn’t recommend running that as a synchronous request.

That said, I can’t see how your code would work. You’re making a cross-domain request, and Dropbox hasn’t enabled CORS (as far as I can see — and I did a couple of initial checks).

Maybe give XHR2 a better read and check out CORS, which is what I think you want.

Bottom line, since you’re hitting Dropbox, unless you do something like a JSONP request (and modify the content appropriately), I don’t think you’re going to be able to achieve what you’re shooting for here.

— Remy

Defining Sections on Home Page and Category Pages

Özer asked:

An example website is www.kahome.com. I have no problem with header footer aside etc. However, I am confused while using article on homepage and category pages.

The homepage contains main menu, an important image, a brief information text, some important seasonal category links (changing seasonally), news section (dynamically changing) and secondary categories at the bottom.

First: Centered main image <div id="orta"> should be tagged as article or not?

Second: <div id="sidebar-2"> with brief company information should tagged as an article or aside? (it is currently aside because of CMS layout but i can change it)

Third: seasonal category links <div id="ana"> is tagged as article. Is it true?

Fourth: for the category page, there is a collection of products and they are completely tagged in <article>. Should each product link be tagged as sub articles (they have just title, image, 3 words description) or is it better to use <section> for each product box?

Last question is about your sectioning system: In html5doctor.com homepage sectioning, “article id=opener” contains a featured article (sub article) and an aside section with recent comments. However there is no top level article in “opener” section.

For “more posts from HTML5 doctor” section, <section> is used as main frame and <article>s are nested in it.

What is the difference between of those two sections and what is the purpose of such usage? (Probably detailed answer to this question will also answer my questions above.) Thank you for your kind interest.

Hi Özer,

  1. The image in the center of your homepage is not an article, it isn’t a standalone piece of content (like a news post or shop product) and appears to be just a nice image to spruce up the homepage. However, if the photo of the table was one of your products and you were using that space to advertise that product with a link through to the product, perhaps some text content like a name and description, that could be considered an article.
  2. If that company information box was just on the homepage as a little introduction, I would consider it just part of the homepage and therefore not an <article>. If it had a heading, I would probably use <section> rather than <div> and make it part of the document outline. See our article on document outlines for more on this.
  3. I would consider the seasonal categories area a <section>, if you added a heading like “Seasonal Categories” to the document outline, and then each category within that could be an article as they summarise the standalone content that is a category page.
  4. I personally don’t see a problem with using <article> for each of your products in a listing. If you think of it like a news feed, perhaps even via RSS, each product is a standalone entity and should be treated as such. We have examples of this in our post about <article> (see the section entitled “A <section> containing <article>s”).

Finally, even though you aren’t marking up a blog, Dr Bruce’s article Designing a Blog with HTML5 may prove useful in helping you understand how and when to use <section>, <article>, and other elements.

Hope this helps! Mike

Outline View

Tarun asked:

I have a very small question, regarding outline view in html5.

Problem is in HTML5 we need a heading tag in each section, article, nav etc. for outline view. But in a document there are many places where we do not need to display any heading for an article, section or nav etc.

So there are two solution i know are below:

  1. Set display none to heading not need to show. But the problem is it’s not good for SEO purpose. Search engine may blacklist if they find lot of sections with display none property.
  2. Set a big value to text-indent so that they will not display, but again same problem. it’s not good for SEO.

Please give me a proper solution for that. Thanks in advance :)

I think <article>s often need a heading (but not necessarily if the <article> is a comment, nested in a parent article). Whether or not you have heading on sections, <nav> is entirely up to your content authors and designers.

If you don’t need them, don’t add them.

— Bruce

HTML5 Element for a Social Bar

Ibo asked:

I was wondering what HTML5 tag to use for the a social bar (Facebook and Twitter links, etc). Is there a common practice for sectioning social links? Should a social bar be defined as a section or should it be as grouping links? Has a tag like <social></social> ever been considered for the HTML5 standard? Could a tag like this be beneficial to SEO?

Even though I might be a rookie at coding html, I take great pride and comfort in coding semantically correct html.

A design I made has a social bar on the very top of the page. Should I include it the header section like I do with the main navigation

Seems to me that a social bar is peripheral to your content rather than introductory or navigation, and therefore shouldn’t be in the <header>. As it’s peripheral, I’d probably put in in <aside> — most likely just a plain old <div>, but either way not in a header.

— Bruce

HTML5 with an Older Site

Clodagh asked:

I have been requested to build a HTML5 area within the confines of a site that is not HTML5. Is this possible and how would it work with doctypes? I would greatly appreciate any advice you can give on this.

Solution #1 (preferred)

Change the doctype for the whole site. Assuming it already has some kind of doctype (and therefore works in standards mode rather than quirks mode), all existing content and functionality will be unchanged and new stuff will be fine.

Solution #2

If you can’t change the doctype, you can use an obsolete permitted doctype — that is, just add the HTML5 areas and leave the doctype alone.

— Bruce

Hidden Headings for Accessibility

Tim asked:

I have been seeing more of these pointers popping up lately advising to place a heading (h1 etc.) before each section in our document telling what the section is. For example, <h1>Site Navigation</h1> placed immediately before the nav that outlines your main site navigation. The presumption in these cases is that you would then be hiding the text via text-indent so that it didn’t appear to visual site visitors, but would be available for sight-disabled users so they know what the section is and so that the document outline is correct and sections. This seems odd to me and I’ve struggled with why. Is this a good practice?

See Webcredible and About.com.

Good question, and I’m considering writing an article about it. It’s come about because it’s well-known that people with screenreaders often navigate a page (or derive a preliminary mental map of its structure) via its heading structure. Here’s a YouTube video by a blind web developer explaining how he does this. In JAWS, for example, a user can hit the H key to jump from heading to heading, hit “2” to go to the next <h2>, “3” to go to the next <h3>, and so on. (This is why I recommend that you don’t make all headings into <h1>s in the hope that the HTML5 Outlining algorithm will deal with it, because until browsers actually understand that, screenreader users will get a completely flat hierarchy. That’s changing, though; Jaws 13 supports the h1-only technique in Internet Explorer 9 and Firefox. See Accessible culture for more).

However, power users of screenreaders have other mechanisms to navigate a page. Since the Webcredible article you cite (dated 2007), many assistive technologies now allow navigation via ARIA landmark roles. HTML5 mints new elements like <nav> and <aside> that have similar semantics to those ARIA roles (ARIA can be used in any markup language, including HTML4 and SVG).

Thus, because a user can get to the <nav> through other means, it can be argued that having a heading “navigation” is redundant. Or not: my own blog has headings for navigation types such as “categories” and “recent comments”, but I don’t have a heading “main nav”, “main content”, or “footer”.

I don’t do it for two reasons. First, it feels redundant to me. The structural semantics are there for user agents to consume. Second, I dislike using CSS to hide content from the view, not because of worries about SEO penalties, but simply because it feels wrong to me.

But your mileage may vary.

— Bruce

Got a question for us?

That wraps up this round of questions. If you’ve got a query about the HTML5 spec or how to implement it, you can get in touch with us and we’ll do our best to help.

Your HTML5 Questions 20 originally appeared on HTML5 Doctor on October 9, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/your-html5-questions-20/feed/ 5
Review: HTML5 Multimedia: Develop and Design https://stevefaulkner.github.io/html5doctored/review-html5-multimedia-develop-and-design/ https://stevefaulkner.github.io/html5doctored/review-html5-multimedia-develop-and-design/#comments Tue, 28 Aug 2012 17:03:18 +0000 http://html5doctor.com/?p=4744

Related Posts:

]]>
With a number of HTML5 books now available, we’re starting to see them cover more specific areas of HTML5. HTML5 Multimedia: Develop and Design, written by fellow HTML5 Doctor Ian Devlin, focusses on native multimedia in HTML5. Read my review below to find out what it’s all about.

Disclosure: Ian is a friend of mine (though I’ve never met him in real life, so I can’t actually confirm he exists), an HTML5 Doctor, and a fellow curator of HTML5 Gallery. This review isn’t biased though.

It’s an honest opinion of the book.

I’ve been meaning to write this review since the book came out — and before Ian joined the surgeons on this site — but I didn’t get around to it. Thankfully much of the book is still relevant.

Although Ian’s book is primarily about HTML5 multimedia, he actually covers much more, including brief introductions to new HTML5 elements, parts of CSS3, canvas, SVG, and WebSockets whilst linking them all back to native multimedia. It’s a comfortable length, easy to read, has solid examples, and dives into lots of detail in places. There’s useful, practical information regarding such things as MIME types and MP4 profiles and other gotchas that you don’t always see in other books and articles. And the best thing: Ian has tested all this himself and not relied on someone else’s word.

Cover of HTML5 Multimedia: Develop and Design Book

HTML5 Multimedia: Develop and Design, by Ian Devlin

The book starts with an introduction to HTML5, including a potted history and some detail about many of the new elements. You can probably skip this chapter if you know a bit about HTML5.

The second chapter is dedicated to the history of web-based multimedia. Ian manages to tell the story in detail without making it boring. I found the web multimedia history lesson very interesting as it reminded me of the pains we endured making sites in the early days of the web. This chapter also introduces the four main multimedia elements (<audio>, <video>, <source>, and <track>) covered in the book, along with their associated attributes.

Chapters 3 and 4 cover <audio> and <video> and their attributes in further detail. It’s well-written and easy to understand with good humour expressed throughout the examples. Ian does perhaps gloss over some of the downsides, such as having to encode and host files multiple times, particularly for commercial sites (although it is mentioned in passing in Chapter 4). This is understandable, though, as native multimedia is still overall a big win for developers and users.

For video in particular, there’s good coverage of media queries and media types and even caveats for Android (or targeting other devices and serving appropriate content). Ian also includes a helpful tip about qtindexswapper that you may have seen in Ian’s recent Multimedia Troubleshooting article.

The next chapter covers the media API. It’s a simple and easy-to-follow introduction for someone (like me) who doesn’t write a lot of JavaScript. Ian shows how to script your own controls, amongst other things. It would’ve been nice to see complete code examples at the end of each section, so you could see exactly where each portion of the script fits in relation to the others.

Chapters 6 and 7 cover styling with CSS. If you’re up to speed with CSS3, then you should find it all simple enough. There’s all your standard rounded corners, gradients, and shadow shizzle included. The object properties and transitions and animation are also covered, which are good to know about.

I do have to question the value of these chapters for readers. Perhaps it’s beneficial for those with little knowledge of CSS, but overall these chapters feel too long and take up a large portion of content that could have been used to explore the API or accessibility (“a11y”) in more detail.

Speaking of a11y, that’s covered in Chapter 8. It includes a thorough introduction to WebVTT, the <track> element, and keyboard interaction. I would have liked to see Ian dig a little deeper and look at other a11y areas that are appropriate to multimedia.

Ian then looks at using video with canvas and SVG. He includes some useful ideas such as taking a screenshot using canvas or grey-scaling a video. For SVG, there are some excellent tips about masking and animating masks over video using SVG shapes (plus a brief intro to SVG for those who haven’t used it). He introduces SVG filters, but it was unclear to me how I link the SVG filters to the actual video files. Again, I think complete final examples would have been good to see here.

The book closes with a useful overview of where native multimedia is heading and introduces a number of new APIs coming soon (or already here in some cases) to a browser near you.

Summary

In summary, the book is easy to read and has an appropriate level of detail throughout with good examples to supplement the explanation. I’d definitely recommend this book to anyone who’s looking to do more with HTML5 Multimedia than simply add it to a site as you see in a lot of tutorials.

Review: HTML5 Multimedia: Develop and Design originally appeared on HTML5 Doctor on August 28, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/review-html5-multimedia-develop-and-design/feed/ 3
Your HTML5 Questions 19 https://stevefaulkner.github.io/html5doctored/your-html5-questions-19/ https://stevefaulkner.github.io/html5doctored/your-html5-questions-19/#comments Tue, 14 Aug 2012 14:30:54 +0000 http://html5doctor.com/?p=4733 As you may have noticed, we've not written one of these posts in a while. That's not down to us not receiving them, though. Government cutbacks have hit health services hard, so decisions had to be made. Well, that and the fact that we've all just been manically busy with our day jobs.

]]>
As you may have noticed, we’ve not written one of these posts in a while. That’s not down to us not receiving them, though.

Government cutbacks have hit health services hard, so decisions had to be made. Well, that and the fact that we’ve all just been manically busy with our day jobs.

Enough waffle, though. We’ll try to get these posts going regularly again. This time, we cover marking up poems, how to add an element to HTML5, using target="_blank", adding text to <canvas>, and which element to use for price or money.

Poem Markup

Gergő asked:

Hi there Doc,

On this site should I mark up the poems as sections or articles?

Thank you so much for your mighty wisdom and super helping hand.

Cheers, Greg from Hungary

I can’t read Hungarian so can’t tell in detail, but I’d use one <article> per poem. If it’s a long poem — e.g. The Waste Land — divide it into sections:

<article>
  <h1>The Waste Land</h1>
  ...
  <section>
    <h2>The Burial of the Dead</h2>
    <p>April is the cruellest month<br>
  Breeding lilacs out of the dead land<br>
  Mixing memory with desire.</p>
    <p>Winter kept us warm ... </p>
  </section>

  <section>
    <h2>The Game of Chess</h2>
    ...
  </section>
  ...
</article>

— Bruce

Adding a New Element to HTML5

Ian asked:

I want to propose adding a new HTML5 element. Do you know who I should write email to?

Join the WHATWG mailing list, and carefully search the archive to see if your idea has already been discussed. If it hasn’t, email the list. Be sure to state a problem and give use cases.

Read more at the WHATWG Wiki.

— Bruce

target="_blank"

Juniper asked:

Howdy Docs,

Just wondering if you’d like to tackle the age old question: now that we have HTML5 and it’s not as fussy as XHTML was, what with it’s fancy X and all, is target="_blank" okay to use again instead of rel="external" and JavaScript?

What was the big deal in the first place?

The answer to the first bit is “yes”.

Regarding What was the big deal in the first place?, target="_blank" assumes a windowed environment and XHTML didn’t want to make any assumptions. Also, opening in this window or that window is behavioural, not semantic, so it should be in the JavaScript layer and not the HTML layer.

— Bruce

Placing Text on <canvas>

Naresh asked:

How can I place HTML text on a canvas? Actually, I have an editable text area where I can add/edit/modify the text like a text editor. Now I want to place this customized text on the canvas. This is the HTML text example:

<p style="text-align: center;"><span style="color: rgb(255, 0, 0);">EVERYDAY SPENT WITH YOU IS A GIFT.</span></p>
<p style="text-align: center;"><span style="color: rgb(255, 0, 0);">ALL MY LOVE</span></p>
<p style="text-align: center;"><span style="color: rgb(255, 0, 0);">Della</span></p>

Thanks in advance.

If you like, you can read the full specification for the 2D drawing API.

But placing text is relatively simple, so long as what you’re doing is straightforward. It gets trickier when you have multiple bits of text, as you need to measure the height of the text and ensure the subsequent lines are clearing the previous lines. For example:

// code goes here!
ctx.fillStyle = 'rgb(255, 0, 0)'; // red

// comic sans == the new black
ctx.font = 'italic 400 18px/2 comic sans ms, sans-serif';
ctx.fillText('Comic sans will always bring funs to dull content', 25, 50); // not

Here’s a working example.

Good luck. — Remy

Marking Up a Price

Fabrizio asked:

I asked this question on Stack Overflow and so far the tag var was proposed. What do you think?

Thanks in advance.

I disagree with using <var> for prices based on the examples you provided. I’ve posted an answer on Stack Overflow and repeated it below.

The HTML spec for <var> states:

The var element represents a variable. This could be an actual variable in a mathematical expression or programming context, an identifier representing a constant, a function parameter, or just be a term used as a placeholder in prose.

To me, this means that <var> is not suitable for the prices in your examples. It depends on what you’re trying to accomplish, but it seems your options are:

  1. Use microdata — for example, Schema.org’s offer vocabulary for a product’s price.
  2. Use the <b> element if you’d like to draw attention to the price without indicating that it’s more important.
  3. Use <strong> if the price is important, such as the total price of an itemised receipt.
  4. Use <span> with a class if you need an element to style the price differently but <b> and <strong> are not appropriate.
  5. If nothing above is suitable and you don’t want to style the price, don’t do anything.

From the examples you’ve given, there doesn’t seem to be any need to mark up prices. If the examples are from a table displaying financial information, make sure they’re in a column headed by <th scope="col">Income</th> or <th scope="col">Price</th>, respectively, for accessibility.

Hope that helps! — Oli

Got a question for us?

That wraps up this round of questions. If you’ve got a query about the HTML5 spec or how to implement it, you can get in touch with us and we’ll do our best to help.

Your HTML5 Questions 19 originally appeared on HTML5 Doctor on August 14, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/your-html5-questions-19/feed/ 12
Latest News: An awards win and DuckDuckGo plugin https://stevefaulkner.github.io/html5doctored/latest-news-an-awards-win-and-duckduckgo-plugin/ https://stevefaulkner.github.io/html5doctored/latest-news-an-awards-win-and-duckduckgo-plugin/#comments Thu, 21 Jun 2012 14:31:38 +0000 http://html5doctor.com/?p=4682

Related Posts:

]]>
Some of our regular readers may remember that last year we won the “Blog of the Year” award at the critters. Well, astonishingly in the face of stiff competition from none other than A List Apart and Gov.uk we’ve managed to win another critter, this time in the “Web Open To All” category.

Critters Logo

Thanks to everyone who voted and to the judges for their votes. We feel really chuffed to have won, with such a small team of guys, writing and maintaining the site alongside our day jobs.

Unfortunately none of us could make it to the awards, which is a shame because the white coats haven’t had an outing for a while. Rest assured though, we’re committed to continuing to create some great content for you guys and have a few other things up our sleeves. In addition, if you have anything that you’d like to see covered or ideas for site developments let us know by commenting or send a mail.

DuckDuckGo Plugin

Before I continue, for those of you that haven’t tried the excellent DuckDuckGo as an alternative to Google, I suggest you check it out.

We were approached a couple of weeks ago by Lucas Sampaio who explain how he was creating a plugin to print HTML5 snippets in DuckDuckGo searches and he wanted to use some of our data. The result is that if you search for a string such as “html details” on DuckDuckGo, you will get a rich snippet at the top of the search results with content from our site as shown in Figure 1.

Screenshot from DuckDuckGo search

Figure 1. Screenshot from DuckDuckGo search for “html details”

The snippet isn’t currently configured for all elements or variations on search phrases but we hope to see it extended in the future. Thanks to Lucas and the DuckDuckGo team for creating it.

Write for us

One last thing that we don’t often shout about is that we’re always on the lookout for locum doctors for the site. If you’ve got something valuable to say about HTML5 and want to write about it, then drop us a line with an article proposal. We’ll consider it and get back to you.

Before you submit your proposal though, be sure to check the article archive to make sure we haven’t covered it in the past.

In the interests of transparency, we don’t pay for writing articles (we don’t pay ourselves either, so you’re not getting a raw deal there) but you will get great exposure for your article.

That’s all for now. Normal service will be resumed in the next couple of weeks.

Latest News: An awards win and DuckDuckGo plugin originally appeared on HTML5 Doctor on June 21, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/latest-news-an-awards-win-and-duckduckgo-plugin/feed/ 1
The output element https://stevefaulkner.github.io/html5doctored/the-output-element/ https://stevefaulkner.github.io/html5doctored/the-output-element/#comments Tue, 20 Dec 2011 14:30:20 +0000 http://html5doctor.com/?p=3976 Across the web, you’ll see a range of sites that feature calculators for working out things like loan repayments, mortgage rates, tax, insurance, and more. Until now, we’ve had no way of semantically marking up the result of those calculations. Enter: the <output> element! In this article, we’ll show you <output> and some related JavaScript tricks. Let’s get cracking.

]]>
Across the web, you’ll see a range of sites that feature calculators for working out things like loan repayments, mortgage rates, tax, insurance, and more. Until now, we’ve had no way of semantically marking up the result of those calculations. Enter: the <output> element! In this article, we’ll show you <output> and some related JavaScript tricks. Let’s get cracking.

The Definition

The <output> element, new in HTML5, is used in forms. The WHATWG HTML specification describes <output> very simply:

The output element represents the result of a calculation.

Along with the standard global attributes, <output> also accepts the following:

for
A space-separated list containing the IDs of the elements whose values went into the calculation.
form
Associates the <output> element with its form owner. The value must be the ID of a form in the same document. This allows you to place an <output> element outside of the <form> with which it is associated.
name
The name of the element.

Implementing <output>

We’ll start by creating a simple example that adds two whole numbers together (Figure 1). We’ll use the new-in-HTML5 number input type and the parseInt JavaScript function to convert the input strings to integers:

<form onsubmit="return false" oninput="o.value = parseInt(a.value) + parseInt(b.value)">
  <input name="a" type="number" step="any"> +
  <input name="b" type="number" step="any"> =
  <output name="o"></output>
</form>
Construction of a calculation using the output element
Figure 1: A simple calculator, rendered in Chrome

Notice that we’re using the now-standard oninput event, which has replaced the deprecated onforminput event. Daniel Friesen has written a detailed article on the background and current support of oninput. oninput isn’t supported in IE8 and below, and its IE9 support is a little flaky, but you can work around these problems using the html5Widgets polyfill.

See a live example of the code in Figure 1.

As you’d expect, if you only enter a single value, the function returns NaN. It’s effectively trying to add a number and an undefined value, and 1 + undefined = undefined.

Using the for Attribute

Let’s build on the previous example and add the for attribute to the <output> (Figure 2). We need to add IDs to each of the associated <input>s, just as we would with the for attribute on a <label>:

<form onsubmit="return false" oninput="o.value = parseInt(a.value) + parseInt(b.value)">
  <input name="a" id="a" type="number" step="any"> +
  <input name="b" id="b" type="number" step="any"> =
  <output name="o" for="a b"></output>
</form>
Figure 2: Using the for attribute on the <output> element

See a live example of the code in Figure 2.

The valueAsNumber Property

HTML5 has also introduced the valueAsNumber property of JavaScript input objects (specifically those of type number, date, and range). This returns the value as a number rather than as a string, meaning we no longer need to use parseInt or parseFloat, and the + operator adds rather than concatenates:

<form onsubmit="return false" oninput="o.value = a.valueAsNumber + b.valueAsNumber">
  <input name="a" id="a" type="number" step="any"> +
  <input name="b" id="b" type="number" step="any"> =
  <output name="o" for="a b"></output>
</form>
Figure 3: Using the valueAsNumber property for retrieving a numeric value from an input

See a live example of the code in Figure 3.

Invoicing Calculator: An In-depth Example with Fallbacks

For a more realistic example, let’s create an invoicing calculator that multiplies the number of hours by the hourly rate and adds tax to give an overall total (Figure 4):

<form onsubmit="return false" oninput="amount.value = (hours.valueAsNumber * rate.valueAsNumber) + ((hours.valueAsNumber * rate.valueAsNumber) * vat.valueAsNumber)">
  <legend>Invoice</legend>

  <p><label for="hours">Number of hours</label>
  <input type="number" min="0" id="hours" name="hours"></p>

  <p><label for="rate">Rate</label>
  <span>£</span><input type="number" min="0" id="rate" name="rate"></p>

  <p><label for="vat">VAT</label>
  <input type="number" min="0" id="vat" value="0.20" name="vat"></p>

  <p>Total: <strong>£<output name="amount" for="hours rate vat">0</output></strong></p>
</form>
Invoice tax calculator using the output element
Figure 4: An invoicing calculator that renders its result in an output element

See a live example of the code in Figure 4.

Nothing too complicated going on there. In fact, the scripting is so simple that even I can do it ;)

A Mildly Controversial Example Using <input type="range">

HTML5 also introduces the range input type, which renders as a slider control in supporting browsers. With this input type, a user can enter an approximate value within a given range without having to be completely precise or directly type a numeric value. For cross browser compatibility, see Remy’s input range polyfill.

While researching this article, I found a number of examples using the <output> element in conjunction with <input type="range"> as shown in Figure 5:

<form onsubmit="return false" oninput="level.value = flevel.valueAsNumber">
  <label for="flying">Flying Skill Level</label>
  <input name="flevel" id="flying" type="range" min="0" max="100" value="0"> 
  <output for="flying" name="level">0</output>/100
</form>
Output example using type=range
Figure 5: Using <input type="range"> with the <output> element

See a live example of the code in Figure 5.

Using <output> to show the current value to the user seems like a perfectly reasonable use case to me, but it isn’t the result of a calculation as the spec describes. I haven’t spoken directly to Hixie about this, but a couple of people on the IRC channel seemed to agree with, so I filed a bug report to request the definition be amended. Since writing this article, the bug has been resolved and the definition loosened meaning the above is now a valid use of output. Hurrah!. I’ll update this article if something changes.

Browser Support and Polyfills

The good news is that all modern browsers support the <output> element to some extent. The bad news is that there are still a few gotchas.

Browser support for the <output> element
Browser Support
Chrome 13+
Safari 5.1+
Firefox* 6+
Opera 9.20+
Internet Explorer 10+

* Firefox does support the <output> element and the oninput event, but it doesn’t support the valueAsNumber property.

All the examples we’ve seen so far should work perfectly in Opera 11.5+, Safari 5.1+, and Chrome 13+. IE, as you might expect, is lagging somewhat, but support for <output> is in IE10 Platform Preview 2, and support for oninput is already in IE9.

In order to work around this in our simple examples, we’ll need to revert to the tried-and-trusted getElementByID and parseFloat (Figure 6):

<form onsubmit="return false" oninput="document.getElementById('o').innerHTML = parseFloat(document.getElementById('a').value) + parseFloat(document.getElementById('b').value)">
  <input name="a" id="a" type="number" step="any"> +
  <input name="b" id="b" type="number" step="any"> =
  <output name="o" id="o" for="a b"></output>
</form>
Figure 6: Using getElementById to support older browsers

See a live example of the code in Figure 6.

While this isn’t ideal, it’s workable until those less-capable browsers die a slow and painful death. Alternatively, you can use polyfills to plug the gaps.

To check support in your current browser, open up Mike Taylor’s support test page.

Polyfills

To support less-capable browsers, there are polyfills such as HTML5 Widgets created by Zoltan “Du Lac” Hawryluk. Zoltan talks you through the process in this detailed article on creating cross browser forms using html5Widgets.

Summary

You probably won’t find yourself using the <output> element all the time, but it’s useful in a whole host of situations. Calculating values on financial sites spring to mind, or outputting the current mouse position, or perhaps the goal difference in a table of sports teams. What other use cases can you think of for <output>? Let us know in the comments!

The output element originally appeared on HTML5 Doctor on December 20, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/the-output-element/feed/ 36
Review: HTML5 Now (DVD) https://stevefaulkner.github.io/html5doctored/review-html5-now-dvd/ https://stevefaulkner.github.io/html5doctored/review-html5-now-dvd/#comments Tue, 04 Oct 2011 13:30:30 +0000 http://html5doctor.com/?p=3624 We all learn in different ways. Some of us are readers or writers, some are kinesthetic learners, some prefer video or audio. If you fall into either of the latter two categories, Tantek Çelik’s DVD HTML5 Now might just be for you.

]]>
We all learn in different ways. Some of us are readers or writers, some are kinesthetic learners, some prefer video or audio. If you fall into either of the latter two categories, Tantek Çelik’s DVD HTML5 Now (Figure 1) might just be for you.

HTML5 DVD
Figure 1: HTML5 Now DVD by Tantek Çelik

Overview

Personally, I’ve never been keen on video-based learning like this. As such, I wasn’t sure what I’d make of HTML5 Now. It turns out I was pleasantly surprised by the format, the content, and the presentation.

Tantek has an natural, engaging presentation style, and his knowledge of the subject area ranks up there with the best of them. He begins with an interesting historical look at HTML and in turn how HTML5 came to be. This section is full of things you might not know about HTML, let alone HTML5.

A few other thoughts:

  • Tantek constantly urges you to get involved and share your experiences.
  • The early parts of the DVD contain in-depth background information on elements and attributes.
  • Tantek presents a clear, concise introduction to <ruby> and friends, even explaining how it’s worked in IE for 10+ years!
  • He introduces his bulletproof HTML5 syntax (using <div>s with class names inside new elements).
  • The accompanying booklet effectively takes notes for you so you don’t have to. Just sit back and enjoy!
  • The DVD also contains the slides shown throughout the presentation and a PDF of the booklet.
  • A few tongue-tied moments help keep it real, not staged or forced. It shows Tantek really cares about the subject.
  • You’ll get some good tips on when to use the new elements. Additionally, some elements are more stable since the DVD was released.
  • Each section is concluded by a brief summary recapping what you’ve learnt.

Words of warning

As is the case with any book or DVD based on the constantly evolving HTML5 specification, parts of the DVD are now out of date. (It was originally released in July 2010.) Look out for these gotchas:

  • Certain sections don’t mention browser support.
  • <u> is now a part of the HTML5 specification.
  • The WebM video codec didn’t exist at the time of production.
  • There is no mention of form attributes and support for the new input types.
  • <canvas> is incorrectly described as a vector format (it’s bitmap).
  • It’s a shame that Tantek only scratches the surface of <video>, <audio>, <canvas>, and SVG. They each deserve their own DVD!

Summary

I’m still not convinced that DVD is the best format for this type of content. As with print, it goes out of date very quickly. Alternatively, you could simply publish the video(s) on a website and make them available on a subscription basis. That way, outdated information could be updated more regularly. That’s a discussion for another day, though, and I’m sure Tantek would be keen to see it happen.

In my opinion, the DVD is better suited to someone who has some prior knowledge of HTML and HTML5. It’s certainly not for beginners, but it does come recommended. You’ll definitely learn something. I’ll leave you with a video of Tantek (Figure 2) discussing the state of HTML5 at the Voices that Matter Conference just before the DVD was released:

Figure 2: Tantek Çelik at the Voices That Matter: Web Design Conference 2010.

Review: HTML5 Now (DVD) originally appeared on HTML5 Doctor on October 4, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/review-html5-now-dvd/feed/ 2