0

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?

1

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')
  );
}
| improve this answer | |
0

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:

$(document).delegate(
  'form#user-login', 
  'DOMNodeInserted', 
  function(){ $('input#edit-name').focus();
});

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

| improve this answer | |
-1

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));
| improve this answer | |
  • This does not seem to actually attach any javascript via preprocess hook. – selfsimilar 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. – paul.linney 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.