0

I am using the following code, which works.

function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'job_node_form') {
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  }
}

The following code doesn't work.

function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'job_node_form') {
    drupal_add_js(drupal_get_path('module','conflict') . '/js/test.js');
  }
}

The code in sites/all/modules/mymodulename/js/test.js is the following.

if (Drupal.jsEnabled) {
  $(document).ready(function() {
    alert("Hello!");
  });
}

When I look at the page source, I can see the JavaScript file is loaded.

Is the inline code timed differently to the code in a JavaScript file?

3
  • 1
    Propably jsEnabled not defened yet, moreover if browser unsupports js, whole code will not able to execute. Try this jQuery(document).ready(function($) { alert('123'); }); in your file or try $form['#attached']['js'][] = array('data' => 'path_to_js_file.js', 'type' => 'file'); Jul 9, 2013 at 20:15
  • Additionally, the script may be loading before jQuery -- what errors do you see in Firebug/Inspector? Try adding the group parameter THEME, or a low weight (see api.drupal.org/api/drupal/includes!common.inc/function/… for options.)
    – Renee
    Jul 9, 2013 at 20:19
  • Or module named mymodule and you try to load file from "conflict" module, that doesn't exists. :) Jul 9, 2013 at 20:28

1 Answer 1

5

With Drupal, instead of using $(document).ready, you should use Drupal behaviors. The equivalent of the JavaScript code in the test.js file shown in the question would be the following one.

(function($, Drupal) {

  Drupal.behaviors.moduleName = {
    attach:function() {
      alert("Hello!");
    }
  };
}(jQuery, Drupal));

I would rather not use drupal_add_js(). Instead, the code can attach JavaScript to the form array, as the following code does.

if ($form_id == 'job_node_form') {
  $form['#attached']['js'][] = array(
    'type' => 'file',
    'data' => drupal_get_path('module','conflict') . '/js/test.js',
  );
}

This attaches the file directly to the form, allowing it to be removed/replaced by another module that implements hook_form_alter(), hook_form_FORM_ID_alter(), hook_form_BASE_FORM_ID_alter().

Using #attached is also the method that Managing JavaScript says it's preferred over drupal_add_js() because the reference to the file is cached, whereas drupal_add_js() requires a function call to add the script to the page. In some case, for example hook_block_view(), drupal_add_js() won't be called when the block is cached, while the #attached array would be added from hook_block_view() before the block is cached.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.