Focus on first form input field or textarea onload page using jQuery

This Javascript basically only sets the focus on the first form input field or textarea of a form when the page is loaded. i use this in my CMS because I hate it when I e.g. have to manually type in a list of emails in a form always click in the first input field to start typing again. This script uses jQuery.

Usage:

All you need to do, is import jQuery and the jQuery.focusfirst.js file which looks like this:

jQuery.fn.focus_first = function() {
  var elem = jQuery('input:visible', this).get(0);
  var select = jQuery('select:visible', this).get(0);
  if (select && elem) {
    if (select.offsetTop < elem.offsetTop) {
      elem = select;
    }
  }

  var textarea = jQuery('textarea:visible', this).get(0);
  if (textarea && elem) {
    if (textarea.offsetTop < elem.offsetTop) {
      elem = textarea;
    }
  }

  if (elem) {
    elem.focus();
  }
  return this;
}


// onload execute focus_first function
jQuery(document).ready(function() {
    jQuery('form').focus_first();   
});

download the example

Comments

Posted on 02-11 by Neil Scott

Thanks for posting this, it makes filling out forms so much more intuitive.

Leave a comment