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.
June 22, 2012 at 8:34 am |
Wouldn’t that be better as:
$(‘[autofocus]:visible:not(:focus)’).first().focus();
No point focusing hidden elements either.