Automatically focus on the username field on the login form

Public

This means that the cursor will automatically shift to the username field instead of the user having to click there. Very convenient.

</> CopyGet raw version
php
  1. <?php
  2.  
  3. /**
  4.  * Implements hook_form_FORM_ID_alter().
  5.  *
  6.  * Form: user_login
  7.  */
  8. function hook_form_user_login_alter(&$form, &$form_state) {
  9. // Automatically focuses the cursor on the username field on the login form.
  10. $form['#attached']['js'][] = array(
  11. 'type' => 'inline',
  12. 'data' => 'Drupal.behaviors.loginFocus = {
  13. attach: function(context) {
  14. jQuery("#user-login #edit-name", context)
  15. .focus()
  16. .triggerHandler("focus");
  17. }
  18. }',
  19. );
  20. }
  21.  
  22. ?>

Comments

doubouil's picture

Since it's a one-liner, you could use directly :

jQuery("#user-login #edit-name", context).focus();

Also, it's always good to use the context parameter.

nicksanta's picture

Thanks for the feedback @doubouil. I've updated accordingly and also added a triggerHandler() to ensure any other focus() events are called.

naptown's picture

Adding the body class name that indicates a user is not logged in will help optimize.

  1. jQuery(".not-logged-in #user-login #edit-name", context)
naptown's picture

Add the body class "not-logged-in" to jquery selector adds some clarity

jQuery(".not-logged-in #user-login #edit-name", context)