1

I made a module, and I want to add a JavaScript file to that module; I enable the module and obvious it works, but I didn't see the JavaScript file that module should take with.

I just put code similar to the following in hook_menu():

function my2form_menu() {
      drupal_add_js(drupal_get_path('module', 'my2form') . '/abc.js');
}

Is it OK?

2
  • this should work, yes - you have several options regarding when to include and in what position etc ..
    – rémy
    Commented May 19, 2012 at 18:10
  • 2
    When hook_menu() implementations are invoked, Drupal is not necessarily outputting a page; that is why the OP doesn't see the JavaScript file added to the page. That apart, the task of hook_menu() is not adding JavaScript files to the page, but returning the definition of the menu callbacks the module implements.
    – avpaderno
    Commented May 19, 2012 at 18:44

2 Answers 2

6

Adding a call to drupal_add_js() directly in hook_menu() doesn't work; the call to drupal_add_js() should be added on the code that is executed when Drupal is outputting a page. This means:

Within a form, Drupal 7 modules can use something similar to the following code, to add a JavaScript file to the currently output page.

$form['#attached']['js'] = array(
  drupal_get_path('module', 'my2form') . '/abc.js',
);

As alternative, if you write the following line in the .info file of a module, the JavaScript file will be added to any page.

scripts[] = abc.js

The path needs to be relative to the directory containing the module; if the file is contained in a sub-directory of that directory, e.g. javascript, the line should be the following one.

scripts[] = javascript/abc.js
0

If you want to add your js to every page, use hook_init, if you only need to add it to some existing forms use hook_form_alter. It all depends on what your module is doing, so a little more background information will get you a better answer.

0

Your Answer

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

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