3

I've got a JS file that I want to add to Admin>Add Content>Certain Content type
After looking at template.php and checking out the function theme_preprocess_node
I tried to add the JS through drupal_add_js(...) but no go.
Now, I know that there's a similar question however my case is about adding
a JS file to a certain page and nothing else (better seperation of JS files).

Thanks.
(Drupal 6)

Asaf
  • 8,106
  • 19
  • 66
  • 116

3 Answers3

12

Check out drupal_add_js() in page template not working.

The gist of it is that calling drupal_add_js() (or drupal_add_css()) during preprocess functions is basically to late, as the markup for the js/css inclusion has already been rendered into a variable. To work around this, you need to overwrite the variable again by calling drupal_get_js() after your addition:

function yourThemeName_preprocess_page(&$variables) {
  // Is this a node addition page for the specific content type?
  // TODO: Adjust the content type to your needs
  // NOTE: Will only work for the node add form - if you want your js to be
  // included for edit forms as well, you need to enhance the check accordingly
  if ('node' == arg(0) && 'add' == arg(1) && 'yourContentType' == arg(2)) {
    // Add your js file as usual
    drupal_add_js('path/to/your/file.js', 'theme');
    // Ensure that the addition has any effect by repopulating the scripts variable
    $variables['scripts'] = drupal_get_js();
  }
}

NOTE: Use preprocess_page, not preprocess_node for this, as javascript inclusion should happen in the page template. Also, Kevins hint on the need to rebuild the theme registry still applies (+1).

Henrik Opel
  • 19,341
  • 1
  • 48
  • 64
  • This is correct! I explain how to add in custom js at theme level here also: http://stackoverflow.com/questions/3051765/drupal-customizing-modules-question/3053291#3053291 – cam8001 Jun 18 '10 at 08:57
  • alright however it seems like this JS file would be loaded on every page, whereas I want it to be loaded on a certain page (waste of load time otherwise) – Asaf Jun 18 '10 at 09:16
  • @ASAF: You seem to have missed the 'TODO' comment in the example ;) – Henrik Opel Jun 18 '10 at 09:36
  • @ASAF: OK, I just added the page checking logic. – Henrik Opel Jun 18 '10 at 10:12
3

Inside your module could you just do a:

function your_module_name_init() {
    if(arg(0) == "some_name") {
        drupal_add_js(drupal_get_path('module', 'your_module_name') . '/your_js_file_name.js');
    }
}

Something like that?

Shimon Rachlenko
  • 5,469
  • 40
  • 51
Anthony
  • 107
  • 1
  • 7
2

After adding the drupal_add_js, did you clear the theme/site cache? That should work.

Kevin
  • 13,153
  • 11
  • 60
  • 87