Drupal Answers is a question and answer site for Drupal developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 3 down vote accepted

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).

share|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');
share|improve this answer


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

share|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 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 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....

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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