How to Make HTML5 Autofocus Work in IE

If you want to use HTML5′s autofocus attribute and make it work in all browsers, here’s an easy way to do it in one line of jQuery. This code will bail out and do nothing if the browser supports HTML5 autofocus.

$(function() {
  $('[autofocus]:not(:focus)').eq(0).focus();
}

How it Works

  1. [autofocus]: Find all attributes with the autofocus attribute…
  2. :not(:focus): …but not the ones that are already focused. This results in a list of length 0 in any HTML5-capable browser, so nothing more will happen.
  3. .eq(0): Get the first one since it doesn’t make sense to focus multiple elements.
  4. .focus(): Set focus to it.
About these ads

One Response to “How to Make HTML5 Autofocus Work in IE”

  1. Nathan Bubna Says:

    Wouldn’t that be better as:

    $(‘[autofocus]:visible:not(:focus)’).first().focus();

    No point focusing hidden elements either.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: