I have added scripts[] = js/add_property.js to my .info file which works perfectly.

That loads the JavaScript for every page though, so how do you do it so that it only loads for the .tpl that it is used in?


If you want to add the Javascript to a single node, you might also implement hook_node_view:

function my_module_node_view($node, $viewmode, $langcode)
  if ($node->nid == MY_NODE_ID) {
    $node->content['#attached']['js'][] = array
      'type' => 'file',
      'data' => drupal_get_path('module', 'my_module') . 'js/add_property.js',

(Solution adapted from https://www.drupal.org/node/1993228).

| improve this answer | |

Within your theme's template.php, you could use theme_preprocess_node() to distinguish between the types of nodes you like to add your JS to. For the desired type, you can use drupal_add_js():

 * Implements theme_preprocess_node().
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->bundle == 'mytype') {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/js/my-js-file.js');
| improve this answer | |


Adds a JavaScript file, setting, or inline code to the page.

| improve this answer | |
  • Thanks I will try node_view in a minute. I had done a google before I asked and it came up with so many ways I ended up confused as to which one to try – Pamela Whittaker Feb 4 '16 at 13:33
  • It should have been 'data' => drupal_get_path('module', 'my_module') . '/js/add_property.js', ); oops there was a missing / but that worked - thanks – Pamela Whittaker Feb 4 '16 at 13:56

If you want to add js to a specific node JS injector works well


Now I'm not sure how to set it to work on different templates....

| improve this answer | |

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.