Attributes – HTML5 Doctor http://html5doctor.com helping you implement HTML5 today Tue, 21 Jun 2016 09:50:49 +0000 en-US hourly 1 The woes of date input https://stevefaulkner.github.io/html5doctored/the-woes-of-date-input/ https://stevefaulkner.github.io/html5doctored/the-woes-of-date-input/#comments Tue, 19 Jan 2016 14:39:31 +0000 http://html5doctor.com/?p=5961

Related Posts:

]]>
One of the many new input types that HTML5 introduced is the date input type which, in theory, should allow a developer to provide the user with a simple, usable, recognisable method of entering a date on a web page. But sadly, this input type has yet to reach its full potential.

Briefly, the date input type is a form element that allows the capture of a date from a user, usually via a datepicker. The implementation of this datepicker is up to the browser vendor, as the HTML5 specification does not tell vendors how to implement the input’s UI.

The input itself can of course be used without using any of its available attributes:

<label for="when">Date:</label>
<input id="when" name="when" type="date">

Or you can specify minimum and maximum date values via the min and max attributes, ensuring that a user can only choose dates within a specific range:

<label for="when">Date:</label>
<input id="when" name="when" type="date" min="2016-01-01" max="2016-12-01">

You can also use the step attribute to specify, in days, how a date can increment. The default is 1.

This of course is the theory and a fine reality it would be, if it were so but alas it is not.

Features

Rather than talk about browser support for the date input type, I will instead talk about the various features that are part of this input type:

The input field

Neither Firefox nor Safari support this input type; it is treated as a simple text field with no formatting and no special interaction.

Microsoft Edge has no special interactions and in fact the input field appears to be read-only.

Chrome and Opera have the same implementations which display a date placeholder (or date value if the input’s value attribute has been set) using the user’s system settings’ date format. There are also some controls that allow the user to clear the input field, some arrows to cycle up and down between values, and an arrow that will open a datepicker (see Figure 1). There are some WebKit prefixed pseudo selectors available that allow you to change the appearance of the various bits within the input date field.

Screenshot of WebKit's native date input on Chrome

Figure 1. – WebKit’s date input field as seen on Chrome

The min and max attributes

All of those browsers that support the date input type also support the min and max attributes.

Chrome and Opera both work fine if both the min and max attributes are set, but the UI is poor when only one of them is set. In these browsers, the date input displays up and down arrows for the user to change each value (day, month, and year). If a date input has a minimum value set at today’s date, then if the user highlights the year and then clicks the down arrow, the year will change to 275760 as the arrows cycle between the valid values and, since no maximum has been set, the default maximum is used (see Figure 2). This has been reported as a bug but has been marked as “won’t fix” as apparently it is the desired behaviour, I disagree.

Screenshot of WebKit's native date input on Chrome showing the year cycling to 275760

Figure 2. – WebKit’s buggy date input field with a min value set but no max

Something similar happens when only a max value is set in that pressing the up arrow will cycle around to the year 0001, which is the default minimum. Again this leads to a very confusing UX for the user, so please use both min and max where possible.

With Android, the setting of these attributes can cause some weird quirks with the datepicker.

The step attribute

None of the browsers tested support the step attribute.

The datepicker

Firefox and Safari do not support the date input type and therefore do not open a datepicker on desktop. But they do open a device’s native datepicker on mobile devices when the date input field receives focus.

Microsoft Edge opens a datepicker, but its UI is very poor (see Figure 3).

Screenshot of the the Edge's datepicker, which displays a list of selectable dates with one highlighted and two buttons at the bottom, once with a tick and the other with an X

Figure 3. – Microsoft Edge’s native datepicker

Chrome and Opera open a fairly decent datepicker on desktop but you cannot style it at all. It looks how it looks (see Figure 4), and there’s nothing that you can do about it, no matter what your designer says. With these browsers you can disable the native datepicker if you want and implement your own, but this will not work with mobile devices. This gives you the best of both worlds: you can implement a nicer datepicker for desktop and let a device use its own native datepicker.

Screenshot of WebKit's native datepicker and date input on Chrome

Figure 4. – WebKit’s native datepicker and date input field as seen on Chrome

All the native datepickers that I tested on Android displayed some sort of confusing display quirks when valid min and max attribute are set. A user is correctly restricted from selecting a date outside of the specified range, but the visual datepickers often display “previous”, “current”, and “next” values for day, month, and year, and the values displayed for “previous” are either empty (in the case of the month) or set to 9999 (in the case of the year, see Figure 5).

Screenshot of the native datepicker on Android 4.3, with a selected date and the previous year set to 9999

Figure 5. – The native datepicker on Android 4.3

Events

Like most of the other input fields, the date input supports the input and changed events. The input event is fired every time a user interacts with the input field, while the change event is usually only fired when the value is committed, i.e. the input field loses focus.

For those browsers mentioned above that support the native date input field, no specific events are fired that will allow you to determine if the user has done anything “date specific” such as opened or closed the datepicker, or cleared the input field. You can work out if the field has been cleared by listening for the input or change events and then checking the input field’s value.

If you have an event listener set up for the change event and one for the input event, changed will never actually fire as input takes precendence.

Conclusion

So, what can we deduce from all this? Should we use the input date type or not? And as usual the answer is “it depends” as only you know what you’re building and how and where it will be used, so it might fit perfectly for your needs or it might not.

I think in general it’s safe to use the input date type on occasions where a min and max does not need to be set as the quirks when these attributes are used are too irritating to ignore. Since not all browsers support a datepicker and you will have to get one from somewhere else to support these browsers, I would also recommend turning off the datepicker for all desktop browsers (using the method linked to above) as this will still allow devices to use their own.

Have fun!

The woes of date input originally appeared on HTML5 Doctor on January 19, 2016.

]]>
https://stevefaulkner.github.io/html5doctored/the-woes-of-date-input/feed/ 11
The W3C App Manifest specification https://stevefaulkner.github.io/html5doctored/web-manifest-specification/ https://stevefaulkner.github.io/html5doctored/web-manifest-specification/#comments Tue, 29 Jul 2014 09:51:22 +0000 http://html5doctor.com/?p=5515

Related Posts:

]]>
By Marcos Cáceres and Bruce Lawson.

Update 26 September 2014 The initial work for Manifest in Chromium M39 is done, and Marcos (more or less) finished coding the processor a few months ago. “I’m hoping to see it in fxos 2.2“, he said from the pool of his gorgeous Malibu home.)

Update 11 November 2014 Web Application Manifest is in Chrome 38.

Update 9 April 2015 Updated implementation status to note App Install banners in Chrome, Opera Android implementation underway. Also show how to link to the manifest (thanks @mathias!) and remove some scary “this may all change” warnings.

Update 18 August 2015 François Beaufort pointed out that “According to the spec https://w3c.github.io/manifest/#h-density-member, the density should actually be a number (not a string)” – amended accordingly.

Update 7 December 2015 Link to my blogpost declaring Progressive Web Apps “ready for primetime”; remove stuff about service_worker manifest member, as it’s gone now because it was useless

Update 19 April 2016 Changed title to “W3C App Manifest” as that’s what most people know it as. Removed stuff about the density member, as it’s dropped.

Manifest? Eh? What? Why?

Many of us who work on the web are actively working to narrow “the gap” between native applications and web applications. (Disclosure: your humble authors, Marcos Caceres and Bruce Lawson work for browser vendors – Mozilla and Opera respectively – and therefore have mortgage-related reasons to convince you this stuff is a good idea.)

But what is that gap? Just a few years ago, that gap was largely technological. If you wanted access to a device’s GPS, you had to write a native app. Nowadays, the situation is improving somewhat: we can now access devices sensors like GPS, camera, and orientation sensors – though we still have a long way to go. Thanks to recent advances in the web platform we now have a platform that can compete with native applications on a more equal footing.

Nowadays, the primary gaps between native and web is not so much technological. It’s user experience. Users simply love installing apps, which live snugly on the homescreen (or the desktop) waiting to be tickled into life with the tap of a finger or the click of a mouse.

Furthermore, native apps work offline by default, and integrate with the facilities provided by the underlying operating system: consider being able to see installed applications in the task switcher. Or being able to control an app’s privacy settings in the same place as apps installed from an app store. In browser land, we are still fumbling around trying to find opened tabs and having to type long and boring URLs to get anything done.

What we need is a method of “installing” web apps so they are indistinguishable from any other app installed on a user’s device. But at the same time, we don’t want to lose the powerful features that are central to the web platform: linkability, view source, and the ability to host our own stuff.

What is “installation”?

At its most basic, “installation” of a web app means “bookmarking” the web application to the homescreen or adding it to an application launcher. There are some pretty obvious things that you, as a developer, would need to provide to the browser so that it can treat your website as an app: the name, icons, etc. There are then more advanced features that you would need, like being able to indicate the preferred orientation and if you want your app to be fullscreen.

The Manifest specification aims to give you a standardised way to do this using JSON. In the HTML page to be “installed”, simply link to a manifest file, thus:

<link rel="manifest" href="/manifest.json">

But what’s in this mysterious manifest file? Glad you asked!

Application name

The application needs a real name or set of names (which is usually not the same as the title element of a document). For this you use the name and the short_name properties.

{
name: “My totally awesome photo app”
short_name: “Photos”
}

The short_name serves as the name for the application when displayed in contexts with constrained space (e.g., under an icon on the homescreen of a phone). The name can then be a bit longer, fully capturing the name of the application. This also provides an alternative way for users to search your app on their phone. So, typing ‘awesome’ or ‘photo’ would find the application on a user’s device.

If you omit the name, the browser just falls back to using <meta name=”application-name”>, and failing that, the <title> element.

Icons

There needs to be an icon associated with a web app, rather than the browser’s icon. To handle this, the manifest has an icons property. This takes a list of icons and their sizes, and format. Having these optional properties makes icon selection really powerful, because it provides a responsive image solution for icons – which can help avoid unnecessary downloads and helps to make sure your icons always look great across a range of devices and screen densities.

{
   "icons": [{
        "src": "icon/lowres",
        "sizes": "64x64",
        "type": "image/webp"
      }, {
        "src": "icon/hd_small",
        "sizes": "64x64"
      }, {
        "src": "icon/hd_hi",
        "sizes": "128x128",
      }]
}

If you omit the icons, the browser just falls back to looking for <link rel=”icon”>, the favicon.ico or, failing that, may even use a screenshot of your website.

Display modes and orientation

Apps need to be able to control how they are to be displayed when they starts-up. If it’s a game, it might need to be in full-screen and possibly in landscape mode. In order to do this, the manifest format provides you with two properties.

{
 "display": "fullscreen",
 "orientation": "landscape"
}

For the display modes, the options that you have are:

  • fullscreen: take over the whole screen.
  • standalone: opens the app with a status bar.
  • minimal-ui: like on iOS, the app is fullscreen, but certain actions can cause the navigation bar and back/forward buttons to reappear.
  • browser: opens your app with normal browser toolbars and buttons.

The nice thing with orientation is that it serves as the “default orientation” for the scope of the application. So, as you navigate from one page to another, your app stays in the correct orientation. You can override the default orientation using the Screen Lock API.

Start URL

Sometimes you want to make sure that when the user starts up an app, they always go to a particular page first. The start_url property gives you a way of indicating this.

{
 start_url: “/start_screen.html”
}

“Scope” of the app

Native applications have clear “boundaries”: as a user, you know when you open a native application that it won’t suddenly open a different application without you noticing. When switching from one native application to another is often pretty clear that you’ve switched applications. These visual cues are often provided by the underlying operating system (think of bringing up the task manager and picking a different application – or pressing “command/alt-tab” on your desktop machine).

The web is very different: it’s a huge hypertextual system where web applications can span multiple domains: you can seamlessly jump from “gmail.com” to “docs.google.com” and as a user have no idea that you’ve jumped form one “origin” to another. In fact, the whole idea that there are boundaries to an application is totally foreign on the Web as, in reality, a web application is just a series of HTML documents (think, “a series of tubes”… no, don’t think that!).

On the web, the only reason we know that we’ve left the scope of one application and entered into another application is because the web designers have been kind enough to make their websites look uniquely different. In case where they haven’t, a lot of users have also been tricked by sites masquerading as another site (the ol’ “phishing attack”).

The manifest format assist with this problem by allowing you to specify a “URL scope” for your application. This scope sets a boundary for an app. It can either be a domain or a directory within that domain.

{
    “scope”: “/myapp”
}

How can I detect if the user “installed” my app?

As a developer, you really should not have to worry about this – the browser will take care of it for you. Firstly, bugging users to install your app is annoying. We’ve all seen this happen in iOS with sites asking users to “add my app to the homescreen”.

Instead, the approach that we take with the manifest is that “installing” is a progressive enhancement. Focus on creating the optimum experience based on what “display mode” the application is in. You will be able to detect and style this with CSS.

@media all and (display-mode: standalone){ ...}

You can use JavaScript matchMedia to test that media query in JavaScript.

Addendum June 2015: In Chromium, you can detect whether a user accepted or dismissed an install banner.

What’s wrong with <meta> tags?

During the specification discussions, it was hotly debated whether to use <meta> tags in HTML rather than make a new format. After all, the Chrome implementation of Add to Homescreen uses <meta> tags, and this has been the natural home for proprietary flimflam since the web began.

The reasons for including a separate file are

  • it saves loading every page of an installable app/site with tons of header info
  • once downloaded, the file sits in the browsers’s HTTP cache.
  • Marcos loves JSON because he’s totally rad

Who is implementing this

The manifest, and Progressive Web Apps are implemented in Chrome and Opera for Android. Implementation is underway in Firefox. You can kinda-sorta do this is a non-standard way in Safari/iOS, too.

Progressive Web Apps are ready for primetime, I believe.

The W3C App Manifest specification originally appeared on HTML5 Doctor on July 29, 2014.

]]>
https://stevefaulkner.github.io/html5doctored/web-manifest-specification/feed/ 6
Responsive images – end of year report https://stevefaulkner.github.io/html5doctored/responsive-images-end-of-year-report/ https://stevefaulkner.github.io/html5doctored/responsive-images-end-of-year-report/#comments Tue, 12 Nov 2013 17:12:26 +0000 http://html5doctor.com/?p=5352

Related Posts:

]]>
It’s nearly two years since I suggested a <picture> element as a strawman proposal as a way to solve the problem of responsive images, so let’s have a look at how we’re doing.

In September there was a big meetup at Mozilla’s Paris office organised by Mozilla’s Marvellous Mr Marcos who’s been very active in the Responsive Images Community Group and did the hard work of actually turning the <picture> strawman into a spec. Such is the combined allure of Marcos and Paris that a rep from Apple showed up – kudos to Edward O’Connor.

The outcome of the meeting was that <picture> isn’t a viable option. Browser makers don’t like the fact that it’s a new element that does the same as <img> (or what <img> should do if we were speccing it today), and that it depends on multiple nested children. I’d based this on the HTML5 <video> and <source> pattern, but Ian Hickson already said “we learnt with <video> and <source> that having multiple elements for selecting a resource is a huge design pitfall”.

The Paris meetup’s most immediate outcome was agreement that srcset + DPR-switching is the right initial step forward (i.e., the 2x, 3x, etc. syntax). (See Marcos’ full write-up for more fun.)

srcset was specified as part of the WHATWG specification and a draft extension to HTML5, based on Edward O’Connor’s imgset in CSS that’s already implemented in WebKit. It’s fair to say that the syntax hasn’t been received with enthusiasm by developers, as it is ugly and unintuitive. But for the simple case of sending a large image to high-dpi displays and not to 1x dpi displays, it’s simple:

<img src="normal.png" srcset="retina.png 2x" alt="otter vomiting">

Browsers with two or more device pixels per CSS pixels (“retina”) get the 2x image; other browsers, including those that don’t understand srcset get normal.png as specified in the traditional src attribute. Hurrah!

This limited version of srcset is already implemented in WebKit nightly, but not shipping, and was about to be implemented in Gecko and Blink when a proposal from Tab Atkins and John Mellor of Google called src-N made a fashionably late entrance.

It’s not the easiest syntax in the world, either, but src-N does address the three main usecases:

  • devicePixelRatio based resolution switching
  • viewport-size based resolution switching
  • art direction

The simplest incarnation – serving high-dpi images only to browsers that can deal with them is

<img src="normal.png" src-1="normal.png 1x picHigh.png 2x" alt="narwhal regurgitating">

An explainer email shows how verbose <picture> can be for a real sites, while a blog post from Tab Explaining The Last Clause of the src-n Grammar shows a more verbose example of src-N while comparing it with its srcset analogue which is, Tab says, “fucking terrible” – much longer and harder to maintain, requiring non-trivial maths.

All the proposals are verbose and tricky. I suspect that this is simply because it’s a really hard problem, but it is one that needs solving. Tim Kadlec’s posts on Why We Need Responsive Images quantify the bandwidth that we currently waste, and wasted bandwidth costs money and slows down the site for users which has a measurable and significant impact on your sales.

Since src-N has been proposed, both Blink and Gecko have decided not to implement srcset which is currently not yet shipping in WebKit. A representative of Apple called src-N‘s use of multiple attribute “a grotesque perversion of the HTML language“, which implies they’re not eager to implement it. (We’ll ignore the irony that the company which gave us a meta tag in HTML to control presentation is accusing others of perverting HTML).

Meanwhile, the src-N explainer says “Ideally, browsers that have already implemented the basic srcset syntax would remove that as soon as possible before sites start to depend on it”, but goes on to note “it would be possible for such browsers to integrate srcset, just like src acts as a fallback”.

Adam Barth, a Blink rep, writes “I’d rather ship something that’s useful today and iterate to improve it in the future than not ship anything for a long time”, which is fair enough – but Henri Sivonen of Mozilla counters “I think srcset should be taken out of the spec ASAP before WebKit ships it and we get stuck with something that doesn’t allow iteration”. The bone of contention – is srcset subsequently extensible?

Given that src-N addresses more usecases than WebKit’s proposed dpi-switching srcset and the similarity of syntax, I wish WebKit would simply alias their nightly code and ship the minimal dpi-switching src-N given above (so src-1 instead of srcset) and argue about discuss extending it later.

But no. So, once again, impasse. Our doctors’ report: must try harder.

Added 13 November 2013: It’s been pointed out to me that srcset is also implemented in Blink, behind the “experimental features” flag. Demo. The point, however, is that it’s not shipping anywhere so no websites rely in it, and it’s not in Firefox or IE.

Added 2 January 2014: Given the impasse described above, the proposed <picture> element has been revived again and new <picture> specification is under development that combines the best features of all proposals. The most important difference from “old” <picture> is that the <source> elements control the src of the <img> element; thus, <img> is an integral part of the construct rather than simply fallback (and thus is unlikely to be omitted by authors, so “old” browsers won’t be left out.)

Responsive images – end of year report originally appeared on HTML5 Doctor on November 12, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/responsive-images-end-of-year-report/feed/ 76
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
HTML5 adaptive images: end of round one https://stevefaulkner.github.io/html5doctored/html5-adaptive-images-end-of-round-one/ https://stevefaulkner.github.io/html5doctored/html5-adaptive-images-end-of-round-one/#comments Wed, 16 May 2012 10:36:45 +0000 http://html5doctor.com/?p=4645 After The Great Vendor Prefix Hullaballoo of April 2012 comes The Great Responsive Images Brouhaha of May 2012. We look at the main competing formats for adding adaptive images to HTML - the <picture> element, and the <img srcset=""> attribute.

]]>
This article is now superseded. A newer version of the <picture> element is being implemented in Blink, WebKit, Firefox. Read Responsive Images Done Right: A Guide To <picture> And srcset for more.

After The Great Vendor Prefix Hullaballoo of April 2012 comes The Great Responsive Images Brouhaha of May 2012.

Adaptive images are the next unsolved mystery of Responsive Web Design. Do you send large high-res images suitable for retina dispays, which are scaled down on smaller, lower res devices and which therefore waste bandwidth? Or do you send low-res images, whch look grotty when scaled up to large screens or high-res displays? Authors have had to rely on elaborate hacks to send different content images (that is <img> in HTML rather than CSS background images) to different types of devices.

By November 2011, I was so frustrated that no specification body was considering the problem that I proposed a strawman <picture> element that re-used the mechanism of HTML5 <video> with its media queries to swap in different source files:


<picture alt="angry pirate">
   <source src=hires.png media="min-width:800px">
   <source src=midres.png media="min-width:480px">
   <source src=lores.png>
      <!-- fallback for browsers without support -->
      <img src=midres.png alt="angry pirate">
</picture>

Around the same time, others independently came to the same idea and were advised to set up a W3C community group to discuss it which they did. However, in January, the HTML5 editor, Ian Hickson, had said

What’s the use case for doing it for images in <img> elements? Typically <img> elements are for content images, where you don’t usually want to adapt anything.

Those web authors in the W3C Resposive Images Community Group soldiered on in frustration that they were they being ignored because the problem itself wasn’t seen as a problem. Then this week, Edward O’Connor of Apple suggested another method, using a new srcset attribute on the <img> element. This complemented a similar suggestion of his from February for img-set in CSS that is already being added to WebKit:

<img src="foo-lores.jpg"
     srcset="foo-hires.jpg 2x, foo-superduperhires.jpg 6.5x"
     alt="decent alt text for foo.">

The numbers “2” and “6.5x” tell the browser the relative resolutions; foo-hires.jpg is 2x the resolution of foo-lores.jpg.

Only a few days later, a variant of Apple’s suggestion was added to the spec.

There are two major differences between <picture> and srcset. The most obvious is that srcset uses the <img> element, which is great because that’s the natural place for images, adaptive or not. (You can’t re-use the <video> + <source> pattern with <img> because it is an empty element so can’t have child elements. O’Connor’s solution uses attributes, which are fine.)

The other major difference is that it doesn’t use Media Queries. With Media Queries, the author is reponsible for thinking up every permuations of viewport size, orientation, dpi, colour depth, aspect ratio and the like, deciding how to cater for them (if at all), identifing the breakpoints and coding them up. This requires a lot of consideration by the author, and makes for verbose code; a page with 20 pictures, each with 5 Media Queries on 5 <source> elements quickly becomes a lot of code.

O’Connor wrote

Why provide a scale factor and not a media query? Well, media queries are claims about UA state, whereas here we’re asserting something about the relationship between the image assets. Also, User Agents should be free to use whichever asset they deem best suited to their current situation, taking into account not just “media-queriable things” like device resolution but also any scaling applied to the <img> with CSS, its width=”” and height=”” attributes, or even things like the current page zoom level.

I have a lot of sympathy with allowing the browser to make decisions about what it knows of the environment (network speed, latency, pixel density, orientation) to choose the best image for the job. The idea is that the author shouldn’t be expected to anticipate and cater for all those variables. What she can do is describe the things she knows about -the images, their size and pixel density- and the browser will make its choice.

That way, when we’re all living in space and looking a 3D holograms, the proximity to a black hole can be detected by the iDroid3000 device (black holes notoriously cause Web hologram negative timespace inversions) and the right image chosen; we don’t need to invent new media queries for event horizon proximity and retrospectively add it to our websites.

There are two problems with the srcset suggestion. The first is highly subjective, but many feel the same: as it exists in the current, first draft of the spec, the syntax is revolting:

<img src="face-600-200-at-1.jpeg" alt=""
srcset="face-600-200-at-1.jpeg 600w 200h 1x,
face-600-200-at-2.jpeg 600w 200h 2x,
face-icon.png 200w 200h">

Of course, this can be improved, and must be. This isn’t just about aesthetics. If the syntax is too weird, it will be used wrongly. As Dr Remy wrote, “Good to see authors have another microsyntax to learn. It’s not like they had any trouble with vendor-prefixes.”

The second problem is that authors don’t want to relinquish control. There are questions of art direction (see the section headed Do I care about art direction?), and many remain unconvinced that the Apple suggestion addresses that; proponents of srcset are convinced that it does address those use cases.

Debate continues, with a full and frank exchange of views. There are understandably hurt feelings, too, because some of those who laboured in the Community Group feel that their wishes and work have been ignored.

As one of those who proposed <picture>, I have a degree of attachment to it. That’s ego. (In fact, I’d be delighted if it were called the <yayBruce> element, but I’m resigned to the unfairness of life.) But I don’t really care which syntax makes the spec, as long as it addresses the majority of use cases and it is usable by authors. I’m just glad we’re discussing the adaptive image problem at all.

So, get involved. Read the discussions and say your piece. And once the dust has settled and the specification is looking stable, we Doctors will write up our diagnosis.

HTML5 adaptive images: end of round one originally appeared on HTML5 Doctor on May 16, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/html5-adaptive-images-end-of-round-one/feed/ 61
The contenteditable attribute https://stevefaulkner.github.io/html5doctored/the-contenteditable-attribute/ https://stevefaulkner.github.io/html5doctored/the-contenteditable-attribute/#comments Tue, 10 Jan 2012 15:10:16 +0000 http://html5doctor.com/?p=3796 For some time now, we’ve been using various technologies to edit and store text within a web browser. Now with the contenteditable attribute, things have got a whole lot easier. In this article, I’ll tell you what this attribute is for, how it works, and how we can take things further.

]]>
contenteditable attribute, things have got a whole lot easier. In this article, I’ll tell you what this attribute is for, how it works, and how we can take things further.

The Basics

First, let’s check out the spec:
The contenteditable attribute is an enumerated attribute whose keywords are the empty string, true, and false. The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the inherit state, which is the missing value default (and the invalid value default).
The contenteditable attribute was mainly intended for providing an in-browser rich-text or WYSIWYG experience. You’ve likely seen this sort of thing in blog-based authoring tools like Symphony or sites like Flickr where you can begin editing page content simply by clicking in a given area. As mentioned above, contenteditable has three possible states:
contenteditable="" or contenteditable="true"
Indicates that the element is editable.
contenteditable="false"
Indicates that the element is not editable.
contenteditable="inherit"
Indicates that the element is editable if its immediate parent element is editable. This is the default value.
When you add contenteditable to an element, the browser will make that element editable. In addition, any children of that element will also become editable unless the child elements are explicitly contenteditable="false".

Code Example

Here’s some example code to get us started:
<div id="example-one" contenteditable="true">
<style scoped>
  #example-one { margin-bottom: 10px; }
  [contenteditable="true"] { padding: 10px; outline: 2px dashed #CCC; }
  [contenteditable="true"]:hover { outline: 2px dashed #0090D2; }
</style>
<p>Everything contained within this div is editable in browsers that support <code>HTML5</code>. Go on, give it a try: click it and start typing.</p>
</div>
    
Putting it together

Live examples

Here are two basic-but-live examples showing what you can do with contenteditable.

Example One

Everything contained within this div is editable in browsers that support HTML5. Go on, give it a try: click it and start typing.
Live text editing
I’ve used CSS to create an obvious visual cue that this area of text is different from the rest. Note that I’ve future-proofed this with <style scoped>, which I covered in my previous article.

Example Two

Chris Coyier of CSS-Tricks pointed out that you can let your users edit the CSS in real-time. Because the <style> element is set to display: none by the user agent, we need to set it to block for this code to work. Try editing the CSS below:
Live CSS editing

Browser Support

Browser support for contenteditable is surprisingly good:
Browser Support for contenteditable
Browser Version
Chrome 4.0+
Safari 3.1+
Mobile Safari 5.0+
Firefox 3.5+
Opera 9.0+
Opera Mini/Mobile N/A
Internet Explorer 5.5+
Android 3.0+
We have to give credit where it’s due and point out that Internet Explorer has supported this attribute since IE5.5. In fact, a very early iteration of contenteditable was . For a more in-depth compatibility table, visit When Can I Use….

Storing the Changes

For this section, I went straight to Doctor Remy for help, as he is much more knowledgeable than me when it comes to storing your data everything.
Depending on the complexity of your editable block, your code could be listening for the enter key (keyCode 13) to save the changes, and the escape key (keyCode 27) to undo the changes. When the user hits enter (assuming it’s a single line of editable content), it would grab the innerHTML of the editable field and send an Ajax post to your server with the change. A simple example of this can be seen on JS Bin: contenteditable saving to Ajax

Conclusion

We’ve repeated the phrase “paving the cowpaths” all over this site, and I’m mentioning it again with the introduction of the contenteditable attribute. The spec finally makes official something that’s been implemented by browser makers for years. Although this is one of the lesser-known new attributes, I bet you’ll find yourself using it more often than you would think. Imagine being able to simply click a block of content and start making changes instantly: making quick corrections to an article in-place, allowing users to edit their comments, or even building spreadsheets within company applications that aren’t hooked up to any sort of back-end user interface. If you can think of other uses for this attribute, then head on down to the comments section and tell us where else you think this could be implemented.

The contenteditable attribute originally appeared on HTML5 Doctor on January 10, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/the-contenteditable-attribute/feed/ 45
Goodbye time, datetime, and pubdate. Hello data and value. https://stevefaulkner.github.io/html5doctored/time-and-data-element/ https://stevefaulkner.github.io/html5doctored/time-and-data-element/#comments Wed, 02 Nov 2011 16:53:08 +0000 http://html5doctor.com/?p=4071 While HTML5 is stable and being implemented we’re still not past losing (or gaining) an element, as demonstrated by the removal of <time> and the addition of <data>. Rather than jumping into the ensuing brouhaha, we’ve spent some time figuring out what this really means. In short? Well… it’s complicated.

]]>
Please note that since this was written, <time>, datetime and (possibly) pubdate have been reinstated, and made more powerful. Doctor Bruce has the low-down in his blogpost The best of <time>s. We preserve this merely to show our grandchildren that we played a role in the Time Wars.

We’ve come a long way in the HTML5 specification’s steady march towards ratification and implementation. The WHATWG’s energy has recently been more on post-HTML5 features that are being added to “HTML The Living Standard”, plus tidying up HTML5 for Last Call. However we’re still not past losing (or gaining) an element, with last week seeing the removal of <time> and the addition of <data>.

: As per the HTML Working Group Chairs request, the W3 HTML5 Editor’s Draft spec has been reverted to include <time>. Note this means it no longer includes <data>. The WHATWG HTML: Living Standard spec is currently the opposite, still retaining <data> but with no <time>. According to Anne Van Kesteren’s post on the WHATWG Weblog, <time> will return to the WHATWG spec taking into account new use cases on the WHATWG Wiki.

TL;DR — it looks like <time> will remain, probably with more permissive datetimes, and <data> will also remain, but it’ll take a little while before the dust settles.

<time> was originally added to allow dates and times to be machine readable, via the datetime attribute. This gives us human-readable content (“yesterday”) plus hidden machine-readable content (“2011-11-02”) with no accessibility problems. It allows for e.g. browsers to offer to localise dates. The pubdate attribute indicating an article’s date of publication was added for HTML to Atom conversion (also removed from HTML5 in this change), and would make it easy for search engines to sort by date. Having permitted dates and times specified in HTML5 (a subset of ISO 8601) allows a validator to check a datetime value is valid.

<time> has been one of the easier elements to understand for authors, as it’s semantically obvious. By comparison the microformats Class-Value pattern for datetimes is clunky.

HTML5 <time> element:

<time class="dtstart" datetime="2011-10-05T09:00Z">9am on October 5</time>

Microformats Value-Class pattern:

<span class="dtstart"><abbr class="value" title="09:00">9am</abbr> on <abbr class="value" title="2011-10-05">October 5</abbr></span>

<time> has been pretty widely used for weblog article publication dates, and has made it into WordPress and Drupal plus being used by Google for search results.

The issues raised about <time> by authors were mainly that it didn’t do everything: it didn’t cover ancient and vague times, time durations, and there was no “last updated” attribute equivalent to pubdate. The other problem is there are a bunch of other less common but similar kinds of data that would also benefit from being machine readable and validatable, such as weights and prices. Minting a new element for each one would (arguably) be a lot of work, so Ian Hickson has added a generic element for these use cases instead — the <data> element, with a required value attribute.

The data element represents its contents, along with a machine-readable form of those contents in the value attribute.

The value attribute contains the machine-readable equivalent of the element’s content. The <data> element can be used as-is as an element equivalent of data-* for marking up private data for scripts (although without the dataset API). It can also be used in conjunction with microdata vocabularies (and potentially microformats), in which case the format of the value attribute is specified by the vocabulary.

This is a welcome addition as it gives us an easy way to duplicate microformats’ Value-Class pattern for more than just the datetimes <time> allowed. However as part of introducing <data>, <time> together with datetime and pubdate have been dropped.

This is controversial, with :

I think this is a bad decision

Steve Faulkner has requested this change be reverted, and comments on the Twitters and blogs (Bruce, WebMonkey, Zeldman) have been mostly ranging from shock to outrage.

This is because while <time> is semantically obvious, <data> is seen as an equivalent to <div> or <span>. However, “semantics for the sake of it” isn’t enough to justify being in the spec, despite the benefits. Another reason for the dismay is many people have had trouble pushing to use HTML5, and having an element removed gives fuel to anyone arguing HTML5 isn’t suitable for production.

What’s wrong with this picture

In On Semantics in HTML, Jens Meiert lists five types of semantics in HTML markup, ordered from most to least meaningful:

  • Standards bodies: elements, attributes
  • Communities: microdata and microformats vocabularies, POSH formats
  • Common sense: functional ID and class names
  • Generic names
  • Obfuscated, random, or presentational names

Demoting datetimes from spec-specified to vocabulary-specified has several effects. For one, it’s more complex. Compare these two examples using <time> and <data> respectively:

Using <time>:

<article>
 …
 <footer>Published <time pubdate datetime="2011-11-03">today</time>.</footer>
</article>

Using <data> plus the BlogPosting schema.org microdata vocabulary:

<article itemscope itemtype="http://schema.org/BlogPosting">
 …
 <footer>Published <data itemprop="datePublished" value="2011-11-03">today</data>.</footer>
</article>

While Google would no doubt love everyone to start using schema.org vocabularies, it’s a big increase in complexity. Adding <time datetime="…" pubdate> is fairly straightforward — learning and implementing microdata plus an appropriate schema.org vocabulary … not so much. Because of this fewer people will implement machine-readable article published dates.

To make matters worse, Google’s Rich Snippets Testing Tool (so presumably Google Search too) understandably does not yet know about <data>. This means if you use <data> to replace <time> now, Google will only see the human-readable text. <data itemprop="datePublished" value="2011-11-03">today</data> is interpreted as datePublished = today, not datePublished = 2011-11-03.

Also, now that specifying a datetime is not part of HTML5 we (presumably) can no longer validate datetime values using the HTML5 validator. Instead our only option is currently doing the two-step with Google’s Rich Snippets Testing Tool. Ironically as schema.org defined dates using ISO 8601, the imprecise dates and durations requested for <time> are now valid for datePublished, even though pubdate is the one usage of datetime everyone agreed on.

Pros & Cons

Ian Hickson and, it seems, browser makers in general are for this change, whereas authors are in general against it (ahem, priority of constituencies). A couple of options would be:

  1. Scrap <data> and allow the value attribute on any element
  2. Add a type attribute to <data> to make it more semantic
  3. Bring back <time>

Unfortunately there are pros and cons for each of these options:

Allow value on any element

This conflicts with microdata, where the values of some elements are their URLs rather than their content. For example, currently <img itemprop="photo" src="http://oli.jp/photo.jpg"> gives the microdata output of photo = "http://oli.jp/photo.jpg". Adding value to the mix means there’d be two machine-readable values, so authors would need to know which elements couldn’t accept value.

Add a type attribute to <data>

This means the HTML5 specification has to specify each approved type value. While not as much work for implementers as a new element for each type of data, it’s still a bunch of work if the browsers actually do anything with that knowledge (like auto-converting type="money" into your currency). If type is required it also limits <data> to the types that are defined.

Bring back <time>

The easiest way to make everyone happy is to keep <time> in addition to adding <data>. However the cons for this are we’d have two confusingly similar but not always interchangeable ways to mark up datetimes, potentially with different rules on what’s a valid datetime. For example, we’d need to mark up an article’s published date and updated date using different syntax. Special cases and exceptions make things harder to teach and learn.

Conclusion

While our private conversation between doctors about this has tended towards the WTF end of the spectrum, I’m personally up in the air about it. Despite the easy response (“bring back <time>!”), this is one of those thorny problems where there’s no simple right answer. WHATWG is performing a delicate balancing act: pragmatically adding only features that have a lot of value, and removing any that don’t make the grade. In this case Hixie decided the cons of <time> (and of removing it from HTML5) outweighed the pros, and <data> is the result.

The one thing that bothers me about Hixie’s argument is that while datetimes are similar to other types of data that <data> now lets us mark up, they’re orders of magnitude more common on the web. Regardless of how it’s marked up, almost all weblog posts have the published date, and the majority of sites have a copyright date in the footer. In these use cases <time> was perfect, and definitely covered the 80%.

In my ideal world I’d like <time> to return, with the addition of a “pubupdate” attribute, and for all dates and times that fall inside HTML5’s definition to use <time>. For datetimes that <time> currently doesn’t cover, and for general use, we’d have <data>. Then again, I’m not sure I’d want to try teaching such intricacies to someone.

What do you think about this? While you’re welcome to just jump on the hogpile, I’d be interested to hear people consider all the pros and cons, and try to come up with a better (or less problematic) solution.

Goodbye time, datetime, and pubdate. Hello data and value. originally appeared on HTML5 Doctor on November 2, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/time-and-data-element/feed/ 60
The scoped attribute https://stevefaulkner.github.io/html5doctored/the-scoped-attribute/ https://stevefaulkner.github.io/html5doctored/the-scoped-attribute/#comments Tue, 13 Sep 2011 13:30:57 +0000 http://html5doctor.com/?p=3634 The scoped attribute for the style element allows you to include styles mid-document that targets a specific element and its children. Depending upon how you look at this, it’ll either be a godsend or a curse. Once you’ve reached the end of this article, I hope you can form your own opinion.

]]>
The scoped attribute for the <style> element allows you to include styles mid-document that targets a specific element and its children. Depending upon how you look at this, it’ll either be a godsend or a curse. Once you’ve reached the end of this article, I hope you can form your own opinion.

Let’s take a quick look at the spec:

The scoped attribute is a boolean attribute. If set, it indicates that the styles are intended just for the subtree rooted at the style element’s parent element, as opposed to the whole Document.

Isn’t this bad practice?

For years, we’ve been told (and have actively told others) to separate content and presentation layers. So why would we introduce something that seems to go against everything we’ve been preaching?

The separation of these layers is still vitally important, but let’s look at a few use cases to shed some light on why this attribute has been introduced. Scoped style provides a W3C-approved way to:

  • Add one-off CSS styles.
  • Add user-defined styles to wiki or CMS content.
  • Add theme-defined styles via CMS plugins.
  • Keep syndicated content together (e.g., keeping example code together with the example).

How does it work?

In this section, I’ll show you how this new attribute will work when it gets rolled out to browsers.

Our starting point

We’ll be using the following code sample as a starting point:

<article>
  <h1>Style Scoped</h1>
  <p>The scoped attribute for the style element will eventually allow for you to include style elements mid-document. To do this, you must mark up your style element with the scoped attribute.</p>
  <section>
    <h2>How does it work?</h2>
    <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
  </section>
</article>

This is a basic example, with two headings and two paragraphs set within the article element.

Adding the scoped attribute

In the next example, we’ll change the foreground color of the second paragraph to red (from whatever was defined in the master CSS file):

<article>
  <h1>Style Scoped</h1>
  <p>The scoped attribute for the style element will eventually allow for you to include style elements mid-document. To do this, you must mark up your style element with the scoped attribute.</p>
  <section>
    <style scoped>
      p { color: red; }
    </style>
    <h2>How does it work?</h2>
    <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
  </section>
</article>

This screenshot shows how things might render in the browser:

How the scoped attribute will render

Backwards compatibility

Unfortunately, scoped style isn’t all puppy dogs and kittens.

Since this newly introduced attribute isn’t understood by current browsers, CSS rules in <style scoped> are just added to the page’s CSS. Therefore, if you were to include a scoped style block mid-page, its declarations would be applied to every matching element in the document, regardless of whether the element were inside or outside of the scope’s range.

For the sake of backwards compatibility, Louis Lazaris has suggested a brand new element called <scopedstyle>. This new element would only be recognised by supporting browsers and ignored by everything else. This way, scoped styles wouldn’t be added to the whole document. Instead, the browser would just throw away the unrecognised <scopedstyle> element and move on.

Browser support

Browser support for <style scoped> (as of )
Browser Support
Chrome 13 No
Safari 5 No
Firefox 6 No
Opera 11.51 No
Internet Explorer 9 No

Currently, the scoped attribute isn’t working in any of the browser alpha versions (Opera.Next, Mozilla Aurora, or WebKit nightly builds). There’s work in progress by Roland Steiner for support in WebKit.

Using <style scoped> today

So you’ve read this article and decided that you need scoped style in your life. What now? Well, just like every other new HTML5 thing, we have a polyfill for it. Simon Madine has created a jQuery scoped CSS plugin on GitHub.

You could also assign a CSS prefix to target the section of your document you want to style. You’d still be able to stick your styles inline, but you’ve also provided a fallback for the older browsers. In fact, Dr. Oli has done just that on his latest article. (View source and search for <div class="faint">.)

Opinions

There’s no denying that we’re breaking backwards compatibility by introducing <style scoped>. To me, this just doesn’t make any sense. I feel this needs to be addressed by either creating a new element like <scopedstyle> or using some protective mechanism like the <!-- and --> delimiters that have been used within <style> and <script> elements.

Let’s not end this article with negative sentiment, though. As with anything, it’s what you make of it. Scoped style is pretty plain vanilla, but if people abuse it, it’ll end up with a bad rap. Dr. Oli has spoken at length about his love for this attribute as it allows him to have live code examples with the CSS in <pre> and also in a <style scoped> within a <figure>.

So now it’s time for you to express your views. What do you think about the new scoped attribute? Do you think it has a future? Should it be fast-tracked into the spec? Or do you think it’s a waste of time that could ultimately end up mixing our content and presentation layers together again? Let us know in the comments!

The scoped attribute originally appeared on HTML5 Doctor on September 13, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/the-scoped-attribute/feed/ 85