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
- [autofocus]: Find all attributes with the autofocus attribute…
- :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.
- .eq(0): Get the first one since it doesn’t make sense to focus multiple elements.
- .focus(): Set focus to it.
Wouldn’t that be better as:
$(‘[autofocus]:visible:not(:focus)’).first().focus();
No point focusing hidden elements either.
Great article! A lifesaver for dealing with IE < 10. I made the following refinements:
$('[autofocus]').filter(':visible:not(:hidden):focusable:not(:focus)').eq(0).focus();
Applying the .filter allows the initial search for autofocus to be done using native DOM calls. I added filters to only process elements that are visible and focusable.
Nice refinement, Richard.
There is no :focusable selector.
What advantage does using native dom calls have?