HTML5 Doctor » html5 http://html5doctor.com helping you implement HTML5 today Wed, 02 Mar 2016 08:08:54 +0000 en-US hourly 1 cite and blockquote – reloaded https://stevefaulkner.github.io/html5doctored/cite-and-blockquote-reloaded/ https://stevefaulkner.github.io/html5doctored/cite-and-blockquote-reloaded/#comments Mon, 04 Nov 2013 17:20:54 +0000 http://html5doctor.com/?p=5283

Related Posts:

]]>
The definitions of the blockquote and cite elements in the HTML specification have recently been updated. This article explains what the changes mean for developers.

Russian translation: Сite и blockquote: перезагрузка

blockquote definition updated

The blockquote element represents content that  is quoted from another source, optionally with a citation which must be within a footer or cite element, and optionally with in-line changes such as annotations and abbreviations.
Content inside a blockquote other than citations and in-line changes must be quoted from another source, whose address, if it has one, may be cited in the cite attribute. [emphasis mine]
– 4.51 the Blockquote element , Berjon et al. 2013

Note the added emphasis indicated via an inline note using square brackets “[emphasis mine]”

What the changes to blockquote mean for developers

Previously in HTML5 it is was not conforming to include citations within blockquote elements. Now it is, as long as the citation content is within a cite or footer element. Citations inside blockquote elements are a common markup pattern (data indicates approximately 60% of blockquote elements include citations), the change to the HTML spec acknowledges this and provides semantic mechanisms to differentiate quoted content from citations.

Example of footer and cite used inside a blockquote:

<blockquote>
<p>As my fellow HTML5 Doctor, Oli Studholme has showed, people seldom quote exactly 
– so sacrosanctity of the quoted text isn’t a useful ideal – and in print etc, 
citations almost always appear as part of the quotation – it’s highly conventional.</p>
<footer>
— <cite><a href="http://www.brucelawson.co.uk/2013/on-citing-quotations-again/">Bruce Lawson</a></cite>
</footer>
</blockquote>

The above example is indicative of what authors are doing anyway, so rather than maintain a theoretical purity which serves no one, the definition has been modified to solve a real problem using existing HTML features, rather than re-inventing the wheel.

An edge case

One of the arguments against allowing use of cite and footer in blockquote to identify citation content is that the quoted content itself may contain these elements. The simple reason for dismissing this argument is that the vast majority of instances of quotations in blockquote elements this will not be the case. Denying the utility of cite and footer for an edge case is another example of theoretical purity that serves  minimal practical purpose.

If the case does arise for you, one method the HTML speccurrently suggests is you comment out the elements from the source (This is still an open issue and advice may change):

(added 20/11/13) In response to feedback the suggestion in the HTML spec is to use a class attribute (a defined extensibility mechanism) on the cite element to identify it as an inclusion from the quoted source:

  <blockquote>
  <p>My favorite book is <cite class="from-quote">At Swim-Two-Birds</cite></p>
  <footer>- <cite>Mike[tm]Smith</cite></footer>
  </blockquote>

cite definition updated

The cite element represents a reference to a creative work. It must include the title of the work or the name of the author (person, people or organization) or an URL reference, which may be in an abbreviated form as per the conventions used for the addition of citation metadata. [emphasis mine]
– 4.51 the Cite element , Berjon et al. 2013

What the changes to cite mean for developers

Previously in HTML5 it is was not conforming to cite an author by name or include other reference information for a creative work in a cite element, the use of cite was reserved (theoretically) to identify the title of a creative work. This was an attempt to rip up a cow path, that authors had created over the last 14 years of the cite elements existence.

Authors railed against the change in definition:

Join me in a campaign of civil disobedience against the unnecessarily restrictive, backwards-incompatible change to the cite element. Start using HTML5 but start using it sensibly. Let’s ensure that bad advice remains fictitious.

Jeremy Keith, 2009

They also provided use cases and real world examples of citation usage. As a result of research, data analysis and discussion, authors can now, again, use the cite element to identify a wider range of references to a creative work; the title of the work or the name of the author (person, people or organization) or an URL reference. What we lose in theoretical purity we gain in utility:

What do you think?

Please read the definitions in HTML 5.1, your feedback as always is welcome!

Big up! to Doctor Oli whose research helped mold the changes made to the cite and blockquote elements. And to Doctor Bruce for insisting that it his right to cite his mum.

cite and blockquote – reloaded originally appeared on HTML5 Doctor on November 4, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/cite-and-blockquote-reloaded/feed/ 35
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/ 100
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/ 20
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
The progress element https://stevefaulkner.github.io/html5doctored/the-progress-element/ https://stevefaulkner.github.io/html5doctored/the-progress-element/#comments Tue, 12 Feb 2013 14:30:16 +0000 http://html5doctor.com/?p=4927

Related Posts:

]]>
When building web sites and web applications, we often need to provide essential feedback to a user informing them of the progress of their request or task, be it uploading a file, playing a video, or importing data.

HTML5 makes life easier for us by defining an element whose sole purpose is just that: the <progress> element.

The HTML5 specification describes it best:

The progress element represents the completion progress of a task.

The task itself is irrelevant, but displaying its progress is not.

Attributes

There are four attributes that are specified for the <progress> element: max, value, position, and labels. Before taking a look at each of theses attributes in turn, here are a few important notes on them:

  • If the value attribute exists, then the progress bar is considered to be determinate (i.e., it has exact limits). Otherwise it is considered to be indeterminate.
  • If the max attribute is not included, the default acceptable range for the progress bar is between 0.0 and 1.0 inclusive.
  • Authors are encouraged always to include the current value and the maximum value (if used) as inline text to the <progress> element so that the information is still visible to users of legacy browsers.

And now let’s take a closer look at the attributes themselves:

Max
The max attribute is a floating point number that indicates how much work the relevant task requires in total before it can be considered complete. The default value is 1.0.
Value
This is a floating point number that represents the current progress of the relevant task. Its value must be greater than or equal to 0.0 and less than or equal to 1.0 or the value of the max attribute if present.
Position
This is a read-only attribute that returns the current position of the <progress> element. This value is equal to value / max for a determinate progress bar and -1 for an indeterminate progress bar (as the position can’t accurately be determined).
Labels
This is also a read-only attribute that returns a list of the <progress> element’s labels (if there are any).

Examples

Let’s now take a look at some examples of how the <progress> element might be used, including how it might be updated via JavaScript.

Simple Indeterminate Progress Bar

<progress id='p'></progress>

Since we have no idea how long the task in hand will take, the browser will simply display the progress bar until the task is complete and we either hide it or replace it with a ‘task complete’ message.

Simple Determinate Progress Bar

<progress id='p' max='70'><span>0</span>%</progress>

And the JavaScript for updating it:

var pBar = document.getElementById('p');
var updateProgress = function(value) {
  pBar.value = value;
  pBar.getElementsByTagName('span')[0].innerHTML = Math.floor((100 / 70) * value);
}

Note that here the progress bar can have a maximum value of 70, so calls to updateProgress will have values between 0 and 70 and that the value is also displayed within the <progress> element so that it is visible as a simple percentage string for users of legacy browsers.

Using <progress> with HTML5 Video

A good example of using the <progress> element is with an HTML5 video, informing the user how much of the video has been played. This won’t be a full example but will just show the necessary HTML and JavaScript.

Given a <video> element with an id of ‘v’:

<progress id='p' max='100' value='0'><span>0</span>% played</progress>

Use this JavaScript:

var video = document.getElementById('v');
var pBar = document.getElementById('p');
video.addEventListener('timeupdate', function() {
  var percent = Math.floor((100 / video.duration) * video.currentTime);
  pBar.value = percent;
  pBar.getElementsByTagName('span')[0].innerHTML = percent;
}, false);

The JavaScript uses the timeupdate event, which is constantly triggered as the video is being played. The value is converted into a percentage value using the video’s duration (full length) and currentTime (where in the video it currently is).

Using <progress> with the File API

Another useful example is how the <progress> element might be used with the File API. Again, this is not a complete example, assuming the existence of a file input and upload button and <progress> element, and code for reading the file. The specification itself has some good code examples of this.

var p = document.getElementById('p');
// 'reader' is of type FileReader
reader.addEventListener('loadstart', function(evt) {
  if (evt.lengthComputable) p.max = evt.total;
}, false);
reader.addEventListener('progress', function(evt) {
  if (evt.lengthComputable) p.value = evt.loaded;
}, false);

Here the loadstart event is used to set the max attribute of the <progress> element, and then the progress event is used to update the <progress> element’s value attribute.

Browser Support

The <progress> element is fairly well-supported in today’s major browsers, although only in version 6+ of Safari (so not on Windows, as the last version there was 5.1) and only in version 10+ of Internet Explorer.

Styling

As is usual with such elements, browsers have their own unique styling for the <progress> element. You can, however, override this to a certain extent using simple CSS.

The default styling tends to consist of an element with rounded corners, a grey background colour, and a green gradient for the actual progress marker.

A screenshot of the progress element in Firefox

The default styling for the progress element in Firefox 18.0.2.

Let’s say we want to style our progress bar for the HTML5 Doctor website, so that it fits in with the design. We’ll remove the bevel and the gradients using only solid colours. The code below will almost do that:

progress {
  color: #0063a6;
  font-size: .6em;
  line-height: 1.5em;
  text-indent: .5em;
  width: 15em;
  height: 1.8em;
  border: 1px solid #0063a6;
  background: #fff;
}

This, however, won’t change the colour of the progress bar itself, which will remain a green colour. We can change this in Firefox, Internet Explorer 10, Chrome, and Safari using a variety of methods which are outlined below.

Firefox

All we need to use here is:

progress::-moz-progress-bar { background: #0063a6; }

and Firefox will display the colour correctly.

A screenshot of the progress bar after custom styling

The progress bar as it appears in Firefox 18.0.2 after being styled.

Chrome and Safari

For Chrome and Safari, we need to use progress::-webkit-progress-value to specify the progress bar colour and progress::-webkit-progress-bar to specify the background colour of the <progress> element itself:

progress::-webkit-progress-bar { background: #fff; }
progress::-webkit-progress-value { background: #0063a6; }

Internet Explorer 10

Actually the CSS above will be fine to style the <progress> element in IE10, but it’s worth noting that this browser interprets the <progress> element’s color value as the colour of the progress bar.

I’ve uploaded some working examples of determinate and indeterminate progress bars for you to see.

Summary

The <progress> element may seem very similar to the <meter> element — which was also introduced in HTML5 — but it can be seen as a more specific kind of <meter> element that’s only used to measure progress of a task. It’s worth bearing this in mind when deciding which one to use.

Since browser support is pretty good, it’s definitely worth using the <progress> element where appropriate, but you should also ensure that you provide textual fallback for legacy browsers as has been outlined above.

The progress element originally appeared on HTML5 Doctor on February 12, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/the-progress-element/feed/ 21
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
Review: Pro HTML5 Accessibility by Joshue O Connor https://stevefaulkner.github.io/html5doctored/review-pro-html5-accessibility-by-joshue-o-connor/ https://stevefaulkner.github.io/html5doctored/review-pro-html5-accessibility-by-joshue-o-connor/#comments Tue, 11 Dec 2012 10:00:48 +0000 http://html5doctor.com/?p=4830

Related Posts:

]]>
Pro HTML5 Accessibility is an exhaustive book. Author Joshue O Connor is senior accessibility consultant with National Council for the Blind of Ireland’s Centre for Inclusive Technology and a stalwart of many W3C working groups.

Don’t be afraid of the title. The book doesn’t assume that you’re a professional accessibility expert – quite the opposite; the first 100 pages don’t really deal with HTML5 at all, but survey the landscape of disability, assitive technologies and W3C WAI-ARIA. The last chapters of the book usefully survey testing methodologies and tools which will be invaluable to the lone developer told “oh, and it must be accessible/ DDA-/508-compliant, too”.

Joshue does an admirable job of explaining how to use HTML5/ARIA to make sites accessible, and gives a thorough overview of how current browsers communicate new widgets (date pickers, sliders, video controls etc) to assistive technology now, rather than in some glorious unspecified future.

He writes engagingly, too: “Remember that the <div> and <span> elements are semantically neutral elements. They have no meaning, poor things, and are merely empty hooks—ciphers for you to do with what you will. They cheer up to no end when you give them meaning. Existential crisis averted!”

I also appreciated Joshue’s pragmatism: “Good semantics are really important, but real-world accessibility is very nuanced—particularly for new content and element types. However, bear in mind that an unencoded ampersand (which will throw a validation error) never resulted in an inaccessible webpage.”

However, I didn’t understand “Having some heading structure, rather than none, on a web document is far more important than merely ensuring the headings are ordered in the correct way.” Surely “merely ensuring the headings are ordered in the correct way” is exactly the same as “having some heading structure rather than none”?

Pro HTML5 Accessibility by Joshue O Connor

It’s also unclear to me why the author chose to markup buttons to control a video player as

 
<div id="back" tabindex="0">
<img src="player/back_button.png" role="button" alt="Jump Back" />
</div>

rather than simply use a <button> element which by default has a role of button and is focussable. But it doesn’t much matter; it gets the job done.

There are some errors which the technical editor should have picked up. Chapter 3 says “JavaScript has some event handlers that can be activated only by using the mouse, such as onClick”, which isn’t strictly true. The same chapter also says “IE 9 doesn’t support the <video> element”, which is just wrong: it does. A cursory code-test would have shown that chapter 5’s example <img scr="myserver/usful_andgroovy_image.png"> won’t work, as there is no scr attribute (it’s obviously a typo for src).

The most significant failing of the book isn’t the author’s fault: it’s the lack of love for presentation that I’ve found endemic in all Apress books lately. For example, the tables in chapter 5 could easily have been formatted for a more attractive presentation, but they look exactly as a basic Word document. Similarly, the multi-page bulleted lists could easily have been a single, multi-column page.

It looks as if Apress just doesn’t care about quality, which is incomprehensible from a publisher. In a publishing environment where ebooks have advantages such as portability, searchability, updateability in case of errors, dead-tree publishers need to work hard to ensure their products remain competitive. They need to play to the traditional strengths of print: beautiful layouts, colours, good design and high-quality paper. We see these in books from Five Simple Steps, Smashing Magazine and A Book Apart. I’ve only seen a PDF of this book, but a previous physical Apress book I own has a paper quality redolent of 1970s East German toilet paper. Certainly Apress has expended no effort at all to lay out the pages for a pleasant read.

That rant aside, the content of this book will be invaluable to a developer new to the world of accessibility, trying to use modern web standards.

Review: Pro HTML5 Accessibility by Joshue O Connor originally appeared on HTML5 Doctor on December 11, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/review-pro-html5-accessibility-by-joshue-o-connor/feed/ 10
Taking Web Audio Offline in iOS 6 Safari https://stevefaulkner.github.io/html5doctored/taking-web-audio-offline-in-ios-6-safari/ https://stevefaulkner.github.io/html5doctored/taking-web-audio-offline-in-ios-6-safari/#comments Tue, 27 Nov 2012 13:30:20 +0000 http://html5doctor.com/?p=4812

Related Posts:

]]>
Playing cached audio for offline use on iOS Safari has long been a challenge that has proved to be mission impossible. But with the advent of the (WebKit-only) Web Audio API, it is now finally achievable — although you still need to jump through a few hoops.

The bad news is that you still can’t cache an MP3 file using Application Cache and then simply load it using an XmlHttpRequest. Safari on iOS 6 will cache the MP3 but then refuse to play it and fail silently (how useful!).

But all is not lost…

Base64 to the Rescue

Because the Web Audio API offers developers direct control over the AudioBuffer, you can now convert data formats on-the-fly and feed them directly to the Web Audio API for playback. For example, if you encode an MP3 file as a Base64 string, you can then decode it to an ArrayBuffer and convert the raw audio data.

Encoding an Audio File

You can easily convert an MP3 file to a Base64 string using OpenSSL. If you are on Mac OS X, it comes pre-installed, so just open up Terminal.app and type the following command:

openssl base64 -in [infile] -out [outfile]

Make sure to replace [infile] with the path to your MP3 and [outfile] with your chosen destination for the encoded data.

This will output a Base64-encoded string representation of your sound file. You can then cache the string using any form of web storage you choose (e.g., Application Cache, localStorage, or webSQL).

Base64 to ArrayBuffer

In order to decode the Base64 string back into an ArrayBuffer, you’ll need to use a custom method. Check out Daniele Guerrero’s base64-binary.js as a good script that can be used exactly for this purpose. It decodes a Base64 string into a Uint8Array typed array and stores it in an ArrayBuffer.

Once this is done, you can simply decode the audio data using the Web Audio API’s decodeAudioData() method:

var buff = Base64Binary.decodeArrayBuffer(sound);

myAudioContext.decodeAudioData(buff, function(audioData) {
  myBuffer = audioData;
});

Once you have the audio data decoded, pass it to your audio buffer source and play the sound:

mySource = myAudioContext.createBufferSource();
mySource.buffer = myBuffer;
mySource.connect(myAudioContext.destination);
mySource.noteOn(0);

Full Demo and Source Code

Check out the online demo and source code for a complete example of the techniques discussed in this article.

Browser Support

Currently the demo works in Safari 6, Chrome Desktop, and iOS 6 Safari. The technique has potential to work in any browser that supports Web Audio API, so hopefully Chrome Mobile can soon add support as well.

The W3C is currently pursuing the Web Audio API as a standard.

Taking Web Audio Offline in iOS 6 Safari originally appeared on HTML5 Doctor on November 27, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/taking-web-audio-offline-in-ios-6-safari/feed/ 11
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
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