HTML5 and CSS3, Second Edition

(singke) #1

Tip 6


Jumping to the First Field with Autofocus


You can really speed up data entry if you place the user’s cursor in the first
field on the form when the page loads. Many search engines do this using
JavaScript, and now HTML5 provides this capability as part of the language.

All you have to do is add the autofocus attribute to any form field:


html5_forms/autofocus/index.html
<labelfor="name">Name</label>
<inputtype="text"name="name"autofocusid="name">

You don’t need to say autofocus="true" or autofocus="autofocus". If the autofocus
attribute is present, the browser will apply the feature.

You can have only one autofocus attribute on a page for it to work reliably. If
you have more than one, the browser will focus the user’s cursor onto the
last autofocused form field.

Falling Back


We can detect the presence of the autofocus attribute and then set focus on the
element with a little bit of JavaScript when the user’s browser doesn’t have
autofocus support. This is probably the easiest fallback solution you’ll come
across. Add this to javascripts/fallbacks.js:

html5_forms/autofocus/javascripts/fallbacks.js
if(!Modernizr.autofocus){
$('input[autofocus]').focus();
}

This uses jQuery to focus the field. We could do this with plain JavaScript,
but we’ve already loaded jQuery, and we can use attribute selectors to grab
the field with autofocus instead of adding a specific class or ID to the field.

Autofocus makes it easier for users to start working with your forms when
they load, but you may want to give them a little more detail about the type
of information you’d like them to provide. Let’s take a look at the placeholder
attribute next.

report erratum • discuss

Jumping to the First Field with Autofocus • 49


Download from Wow! eBook <www.wowebook.com>

Free download pdf