Skip navigation
code text in different colors set at an angle to the picture frame

Working with HTML5 Web Forms: Autofocus and Placeholder Attributes

Help your users by providing focusable and self-describing input fields

Most web developers are well aware of the challenges of building an effective input form. As you know, HTML offers just a basic input field that can accept only text. This means that restricting input to, say, numbers requires extra coding. Accomplishing this would be easy if it were simply a matter of filtering out everything except digits. Instead, most input fields end up being decorated with several short and repetitive pieces of code that filter on accepted characters, focus assignment, post validation, watermark text, and so on. Input forms also require code to handle input of specific data types, such as dates, times, numbers in a known range, and optional values from a predefined list. Padding web pages with tons of JavaScript calls to perform the same tasks for input forms is error prone, and such code is ugly to read and maintain.

Even though I eagerly welcome the new attributes of the element in HTML5, I realize that the input-form support that browsers currently offer isn't uniform, and in some browsers -- most notably Internet Explorer (IE), including version 10 -- it's insufficient. (The Modernizr library helps a lot with detecting browser support for HTML5 features and does a good job with input types and related attributes.) We'll continue our exploration of HTML5's support for input forms, begun in "Simplify Web Form Validation Using HTML5," with a look at the support HTML5 offers for handling focus and watermark text.

Setting the Focus Automatically

As surprising as it might seem, for years we had a programmatic method to set the keyboard focus to an input field. The following jQuery code does the trick, setting the input focus to the first text field. By using a more restrictive Cascading Style Sheets (CSS) selector, you can apply the focus to the first text field of any form.

HTML5 defines a new, ad hoc autofocus attribute for the element just for this purpose. To try out this new attribute, place the following code in the body of a new HTML page.


This code works beautifully on all major browsers that support HTML5, including IE10. For backward compatibility, the autofocus attribute is ignored on older browsers.

Setting the Watermark Text

When you look at an HTML form from the perspective of an end user, it's often hard to figure out which content goes in which field. Most forms offer labels and descriptive text, but end users often don't read much of the content on a displayed page. Perhaps this is why designers have gotten into the habit of asking developers to include in input fields a short amount of text that instructs users about the content to enter in the field.

Before the advent of HTML5, you could accomplish this only by using a bit of JavaScript code. Thankfully, HTML5 provides an ad hoc placeholder attribute that you use to define the watermark text to display when the field is empty. Displaying and hiding the watermark text is left to the browser. Here's an example of using the placeholder attribute.


This attribute is probably one of the few new HTML5 features that has no impact at all on older browsers in the sense that it isn't as potentially detrimental as other features (e.g., validation against regular expressions or date pickers) if not supported by the browser. I suggest you incorporate the placeholder attribute in any HTML form you write.

Validating Against Regular Expressions

In an input form, sometimes you need to collect data as plain text -- but only certain data, such as postal codes or phone numbers. In such cases, you might want to define a pattern that any input for the field should match. Before HTML5, you could achieve this only by performing a client-side validation hooking up the form-submission event. HTML5 lets you shift this burden to the browser so that you get a free (and effective) validation when the form is submitted, by using the new pattern attribute.

You can set the pattern attribute using a valid regular expression. Here's an example:


The PIN field is acceptable only when the entered value takes the form of two letters followed by six digits. Figure 1 shows how Firefox handles an input field when content that doesn't match the required pattern is entered.

Figure 1: The HTML5 Pattern Attribute, as Managed by Firefox

Note that you should provide the title attribute to describe the pattern the input field honors. Providing the title attribute tells the browser that, when it encounters some invalid content, to concatenate a standard message (e.g., Please match the requested format) with the specified text, as shown in Figure 1. Note also that the pattern attribute is fully checked only upon form submission. Thus you should not expect the browser to display any feedback as the user tabs out of the field. This behavior is consistent across all current HTML5-compliant browsers: Opera, Safari, Chrome, Firefox, and IE10.

Currently Firefox applies a different CSS style on the blur event of input fields if the existing content is invalid. Firefox users will see a red border if the pattern isn't honored but won't be prompted with a message. However when you use the title attribute, your users will be able to see and receive guidance from the tooltip, as Figure 2 shows.

Figure 2: Firefox Prompting for Missing Information

Styling the Placeholder Text

By default, browsers render placeholder text in a light gray color. But what if you want to customize the placeholder style a bit? Although all HTML5 browsers are consistent about the implementation of the placeholder attribute, they aren't as consistent about styling. Opera doesn't support it as of version 12. Other browsers do -- but each uses a custom CSS selector.

Here's the code you need to customize the placeholder text color.

As you might have guessed, the webkit selector works for Chrome and Safari, the moz selector works for Firefox, and the ms selector works for IE10. Most of the time, you'll just want to use a different, lighter color. Changing the background color is also possible, but browsers might differ in how they handle this change. In particular, IE10 and Firefox reset the input-field style as soon as the field gets the keyboard focus, whereas Chrome doesn't reset the style until the user starts typing.

The preceding code snippet contains something you might have thought was a typo. The webkit-input-placeholder selector is prefixed with a double colon; others are prefixed with a single colon. Why the difference? In CSS3, the double colon indicates a pseudo-element -- namely, a part of an element you want to style. The placeholder part of the input element is good example of a pseudo-element. Before CSS3, both pseudo-elements and pseudo-classes were represented with the single colon. The point is that the double colon for pseudo-elements in CSS3 isn't currently matched by Firefox and IE10.

You can use different styles for the placeholder text of input fields and textarea elements as well as for different input fields in the same page or form. For this to happen, you simply prefix the selector with whatever text selects the element(s) of interest. For example, the following style gives a different appearance to the placeholder of input and textarea elements. (The demo refers to Chrome, but the same applies to other browser-specific selectors.)

Once you know which selector to use to address the specific placeholder section of the input element, what you can do is limited only by your creativity. For example, you can also place a bitmap within the input field that will disappear along with the descriptive text as the user starts typing or will just set the input focus. The following code shows this, using a slightly different style from that shown in the previous example. For simplicity, the example refers to WebKit browsers only, but you can easily specify other browser engines.

Styling the Input Focus

The pseudo-class focus in CSS is nothing new. When the focus pseudo-class is applied to a selected bunch of elements, it allows you to define the appearance of those elements when they're given the input focus -- and it works beautifully across most browsers. For example, the CSS in the following example adds a yellow background to any focused input field.

As you can see, this pseudo-class isn't specific to HTML5 and CSS3. Some modern browsers (specifically, Chrome) automatically adjust the border around the active input field. You can control that setting using the outline attribute, as follows:

In this way, you get a behavior for focused input fields that's entirely under your control and works across all browsers.

Using the CSS I've shown in the previous examples, you can control focus for just about any input element, including buttons and check boxes. But how can you limit the focus to only input text fields? When using HTML5, I feel that the easiest method to accomplish this is by applying a customized focus appearance only to input fields with a placeholder attribute.

This approach gets you in the habit of using placeholder text on fields where the user is forced to enter text and provides an easy way to select focusable fields.

HTML5: A Boon for Web Forms

Although as mentioned earlier I have conflicting feelings about HTML5, I'm glad it's here because it represents a long-overdue upgrade and fixes many gaps in the previous version of HTML. In my opinion, HTML5's most significant changes are those around web forms and data entry. In this article and the previous one, we explored some of those changes -- changes that make it much easier to work with input-form features such as required-field validation, focus, and watermarks.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish