You are here

function focus_form_alter in Autofocus 5

Same name and namespace in other branches
  1. 6 focus.module \focus_form_alter()
  2. 7 focus.module \focus_form_alter()

Implementation of hook_form_alter(). Add javascript (jQuery) to set focus on the first field in the defined forms.

File

./focus.module, line 70
Simple module that sets focus on the first field in a form.

Code

function focus_form_alter($form_id, &$form) {
  global $_focus_exit;
  $type = $form['type']['#value'];

  // Get default or user defined forms
  $focus_forms = variable_get('focus_forms', FOCUS_FORMS);

  //Replace user variable !type with the node type
  $focus_forms = strtr($focus_forms, array(
    "!content_type!" => $type,
  ));

  // Create an array
  $focus_forms = preg_split("/[\\s,]+/", $focus_forms);

  // If thera are several forms on the same page, only add the javascript for the first one.
  // Don't set focus on edit forms as it can interrupt with user scrolling the page.
  if (!$_focus_exit && arg(2) != 'edit') {
    foreach ($focus_forms as $focus_form) {

      // Check if this form is listed to have focus.
      if ($focus_form == $form_id) {

        // Add the javascript for the first input field, not including hidden input fields.
        $jquery_snippet = '$(document).ready(function(){$("#' . $form['#id'] . ' input").not("[@type=\'hidden\']")[0].focus()});';
        drupal_add_js($jquery_snippet, 'inline');

        // Don't add javascrip for another form.
        $_focus_exit = true;
      }
    }
  }
}