I want a “set focus to first field” script that is simple, generic and smart enough to work 95+% of the time. Here is what I came up with:
var pageBody = '#page-body'; // set this to be your main content area (avoid always setting focus to a search or login form in the header)
$(pageBody + ' form:visible:first:has(:input:visible) :input:visible:first').focus();
Pretty simple:
- Define a scope in which to look for forms. I particularly want to avoid search and login forms in the header, and perhaps email signup forms in the sidebar or footer.
- Find the first form that is visible on the page that also has a visible input element. This avoids forms that are hidden (perhaps that slide open, etc.).
- Set focus to the first visible element in that form.
This is working well in some unscientific sample testing, but I’m curious to see if the “wisdom of the crowd” can help refine it further.
Semi-related question: Does doing this have accessibility concerns? For instance would it mess with screen readers or general keyboard accessibility?
May not be an issue in your use case, just wondering what your thoughts about this type of behavior were in general.
I can’t imagine it would…
Sorry for going off topic. I could have sworn I read something about it not long ago, but I can’t dig up any source material on it so I must have been mistaken.
What if the “first” form field is not an element, but, say, a SELECT, TEXTAREA, or other form field type?
whoops. That should read “…not an INPUT element…”. Sorry.
You’re right, I actually transcribed it wrong here when I was generalizing it, it should be :input.
http://docs.jquery.c[...]ectors/input
I’ve updated the code above.