Canonical “Focus on First Field” jQuery

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:

  1. 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.
  2. 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.).
  3. 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.