Adding javascript to a node content field

If you try to add javascript within a node field and it gets stripped out - even when using the 'PHP code' text format - check out the drupal_add_js function.

Commonly used in modules, it can also be used in content fields too. Just make sure you are entering the code in a field that is using the 'PHP code' text format.

Here are some examples:

  // This will add a JS file to your head (specifically the $scripts variable in page.tpl.php)
  drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js');

// This add inline JS to the head of the document
  drupal_add_js('alert("Hello!")', 'inline');

// This will add variables in the Drupal.settings object
  drupal_add_js(array('my_module' => array('my_setting' => 'this_value')), 'setting');

For more info check out the function drupal_add_js API page (where these examples are lifted from).

Justin Chevallier

Justin Chevallier

Avid Drupal site builder & user for +10 years.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.