The Right Way to Include Javascript in Your Drupal Form

harry.pottash's picture

Often clients want a touch of singing dancing javascript magic on one of their drupal forms. It seems like the right way to include that javascript file is to create a module that looks something like this:

function hook_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'form_in_question'){
    drupal_add_js(
      drupal_get_path('module', 'switchback_nodeform') 
        . '/my_custom_javascript.js');
   }
}

But it turns out that this code is subtly flawed. If the user misses a required field, or has any other form error, when the form is re-loaded your javascript will be absent. In order to make sure that your javascript is always available on that form you actually need to write code like this:

function hook_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'form_in_question'){
     $form['some_element']['#after_build'] = array('_load_my_javascript);
   }
}

function _load_my_javascript($element){
    drupal_add_js(
      drupal_get_path('module', 'switchback_nodeform') 
        . '/my_custom_javascript.js');
return($element);
}

This ensures that your javascript will get pulled in, even when the page is reloaded.

Comments

Thanks for the code. I think this is a good method, but it might be worth mentioning that Damien Tournoud described it as "makes little sense" on http://drupal.org/node/322290.

I normally use the method mentioned by Damien Tournoud, but when I've no need to retheme the form aside from trying to include a js or css file, I find the method mentioned here far faster/easier to implement.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Switchback Caravan logo

Caravan is a powerful and full-featured membership management system, designed specifically for membership- driven organizations.

Caravan Member Managment

Switchback Trailhead logo

Trailhead is a Drupal-based system, built with the features smaller businesses need, bundled together into a ready-to-launch package.

Trailhead CMS Packages

On the Trail Blog