I have working code in my theme's template.php file that adds "autofocus" to my modal login form, but Firefox ignores ajax autofocus fields (only applies autofocus on pageload). So I'm trying to add some js to set focus when the modal login form is called. I currently add autofocus via:

function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['rendered'] = drupal_render_children($variables['form']);

And I'm trying to add js to set focus as a fallback this way:

function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['form']['#attached'][js][] = path_to_theme() . "/js/focus.js";
  $variables['rendered'] = drupal_render_children($variables['form']);

but this doesn't seem to add the js as expected. How can I add either inline or external javascript to my modal login form?


A preferred solution I would use for adding/editing forms would be to use a module hook.

function MODULE_form_user_login_alter(&$form, &$form_state, $form_id) {

  $form['#attached']['js'] = array(
    drupal_get_path('theme', 'THEME') . '/js/focus.js',
    '/* inline js here */' => array( 'type' => 'inline')

I couldn't get any of the dynamic insertion of javascript to work at all, so I ended up adding the following to my site-wide javascript file:

  function(){ $('input#edit-name').focus();

This is, of course, wrapped in the proper (function ($) { Drupal.behaviors.mytheme = { ... namespacing, etc.


Use the standard drupal_add_js https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7

drupal_add_js(drupal_get_path('theme', 'THEME') .'/js/focus.js', 'file');
drupal_add_js('(function ($) { ... })(jQuery);', array('type' => 'inline', 'group' => JS_THEME));
  • This does not seem to actually attach any javascript via preprocess hook. Jun 14 '13 at 17:25
  • To be fair I wasn't too sure myself. I tried it too and I couldn't get it to work. Jun 15 '13 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.