Community Documentation

drupal_add_js

5 common.inc drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE)
6 common.inc drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE, $preprocess = TRUE)
7 common.inc drupal_add_js($data = NULL, $options = NULL)
8 common.inc drupal_add_js($data = NULL, $options = NULL)

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

The behavior of this function depends on the parameters it is called with. Generally, it handles the addition of JavaScript to the page, either as reference to an existing file or as inline code. The following actions can be performed using this function:

  • Add a file ('core', 'module' and 'theme'): Adds a reference to a JavaScript file to the page. JavaScript files are placed in a certain order, from 'core' first, to 'module' and finally 'theme' so that files, that are added later, can override previously added files with ease.
  • Add inline JavaScript code ('inline'): Executes a piece of JavaScript code on the current page by placing the code directly in the page. This can, for example, be useful to tell the user that a new message arrived, by opening a pop up, alert box etc.
  • Add settings ('setting'): Adds a setting to Drupal's global storage of JavaScript settings. Per-page settings are required by some modules to function properly. The settings will be accessible at Drupal.settings.

Parameters

$data: (optional) If given, the value depends on the $type parameter:

  • 'core', 'module' or 'theme': Path to the file relative to base_path().
  • 'inline': The JavaScript code that should be placed in the given scope.
  • 'setting': An array with configuration options as associative array. The array is directly placed in Drupal.settings. You might want to wrap your actual configuration settings in another variable to prevent the pollution of the Drupal.settings namespace.

$type: (optional) The type of JavaScript that should be added to the page. Allowed values are 'core', 'module', 'theme', 'inline' and 'setting'. You can, however, specify any value. It is treated as a reference to a JavaScript file. Defaults to 'module'.

$scope: (optional) The location in which you want to place the script. Possible values are 'header' and 'footer' by default. If your theme implements different locations, however, you can also use these.

$defer: (optional) If set to TRUE, the defer attribute is set on the <script> tag. Defaults to FALSE. This parameter is not used with $type == 'setting'.

$cache: (optional) If set to FALSE, the JavaScript file is loaded anew on every page call, that means, it is not cached. Defaults to TRUE. Used only when $type references a JavaScript file.

$preprocess: (optional) Should this JS file be aggregated if this feature has been turned on under the performance section?

Return value

If the first parameter is NULL, the JavaScript array that has been built so far for $scope is returned. If the first three parameters are NULL, an array with all scopes is returned.

▾ 26 functions call drupal_add_js()

color_scheme_form in modules/color/color.module
Form callback. Returns the configuration form.
comment_form in modules/comment/comment.module
Generate the basic commenting form, for appending to a node or display on a separate page.
drupal_add_tabledrag in includes/common.inc
Assist in adding the tableDrag JavaScript behavior to a themed table.
drupal_get_js in includes/common.inc
Returns a themed presentation of all JavaScript code for the current page.
form_expand_ahah in includes/form.inc
Add AHAH information about a form element to the page to communicate with javascript. If #ahah[path] is set on an element, this additional javascript is added to the page header to attach the AHAH behaviors. See ahah.js for more information.
install_tasks in ./install.php
Tasks performed after the database is initialized.
locale_update_js_files in modules/locale/locale.module
Update JavaScript translation file, if required, and add it to the page.
node_filter_form in modules/node/node.admin.inc
Return form for node administration filters.
openid_form_alter in modules/openid/openid.module
Implementation of hook_form_alter : adds OpenID login to the login forms.
system_clean_url_settings in modules/system/system.admin.inc
Form builder; Configure Clean URL settings.
system_date_time_settings in modules/system/system.admin.inc
Form builder; Configure the site date and time settings.
theme_fieldset in includes/form.inc
Format a group of form items.
theme_poll_choices in modules/poll/poll.module
Theme the admin poll form for choices.
theme_profile_admin_overview in modules/profile/profile.admin.inc
Theme the profile field overview into a drag and drop enabled table.
theme_table in includes/theme.inc
Return a themed table.
theme_table_select_header_cell in includes/theme.inc
Returns a header cell for tables that have a select all functionality.
theme_taxonomy_overview_terms in modules/taxonomy/taxonomy.admin.inc
Theme the terms overview as a sortable list of terms.
theme_textarea in includes/form.inc
Format a textarea.
theme_textfield in includes/form.inc
Format a textfield.
user_admin_settings in modules/user/user.admin.inc
Form builder; Configure user settings for this site.
user_filter_form in modules/user/user.admin.inc
Form builder; Return form for user administration filters.
user_register in modules/user/user.module
Form builder; The user registration form.
_batch_progress_page_js in includes/batch.inc
Batch processing page with JavaScript support.
_book_add_form_elements in modules/book/book.module
Build the common elements of the book form for the node and outline forms.
_init_theme in includes/theme.inc
Initialize the theme system given already loaded information. This function is useful to initialize a theme when no database is present.
_user_password_dynamic_validation in modules/user/user.module
Add javascript and string translations for dynamic password validation (strength and confirmation checking).

File

includes/common.inc, line 2203
Common functions that many Drupal modules will need to reference.

Code

<?php
function drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE, $preprocess = TRUE) {
  static $javascript = array();

  if (isset($data)) {

    // Add jquery.js and drupal.js, as well as the basePath setting, the
    // first time a Javascript file is added.
    if (empty($javascript)) {
      $javascript['header'] = array(
        'core' => array(
          'misc/jquery.js' => array(
            'cache' => TRUE,
            'defer' => FALSE,
            'preprocess' => TRUE,
          ), 
          'misc/drupal.js' => array(
            'cache' => TRUE,
            'defer' => FALSE,
            'preprocess' => TRUE,
          ),
        ), 
        'module' => array(), 
        'theme' => array(), 
        'setting' => array(
          array('basePath' => base_path()),
        ), 
        'inline' => array(),
      );
    }

    if (isset($scope) && !isset($javascript[$scope])) {
      $javascript[$scope] = array(
        'core' => array(),
        'module' => array(),
        'theme' => array(),
        'setting' => array(),
        'inline' => array(),
      );
    }

    if (isset($type) && isset($scope) && !isset($javascript[$scope][$type])) {
      $javascript[$scope][$type] = array();
    }

    switch ($type) {
      case 'setting':
        $javascript[$scope][$type][] = $data;
        break;
      case 'inline':
        $javascript[$scope][$type][] = array(
          'code' => $data,
          'defer' => $defer,
        );
        break;
      default:
        // If cache is FALSE, don't preprocess the JS file.
        $javascript[$scope][$type][$data] = array(
          'cache' => $cache,
          'defer' => $defer,
          'preprocess' => (!$cache ? FALSE : $preprocess),
        );
    }
  }

  if (isset($scope)) {

    if (isset($javascript[$scope])) {
      return $javascript[$scope];
    }
    else {
      return array();
    }
  }
  else {
    return $javascript;
  }
}
?>

Comments

Some Quick Examples

A few quick examples of how to use this function:

<?php
 
// 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');
?>

If you need to add an external JS file to your site, you should probably look at http://api.drupal.org/api/function/drupal_set_html_head/6

My module cannot add any js

My module cannot add any js file with:

drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js');

I checked that the path is correct and the file has correct permissions. Is there another thing to do before it?

Edit: I found out that js optimization was enabled and it prevented the new file from loading. (admin/settings/performance). I disabled it for a the time...

Building On Settings

A useful if somewhat confusing feature of this function is that, at least with settings (I haven't tried w/ other types), calls to this function are additive. Consider the following:

...
drupal_add_js(array('myNamespace' => array('widgets' => array('foo')), 'setting');
drupal_add_js(array('myNamespace' => array('widgets' => array('bar')), 'setting');
drupal_add_js(array('myNamespace' => array('widgets' => array('baz')), 'setting');
...

If you examine the internal $javascript array after these calls, you'll see that each widget is added separately, they are not part of the same scope within the array. However, when the JS is themed, they will be. Based on the above example, here's what the client-side JS will look like:

jQuery.extend(Drupal.settings, { ..."myNamespace": { "widgets": [ "foo", "bar", "baz" ] }, ... });

Cheers

Was looking for a way to avoid this.

Looking for a way to avoid this.
If a setting gets added on each node load then the same setting can get several entries if the node is loaded more than once per page (though it's data is cached.)

Just used $op = 'view' for now since that MOSTLY only happens once per page in my node example... but still think there should be a way to do some sort of drupal_add_js_once().

How to add a JavaScript file to a single page?

I did a search for "How to add a JavaScript file to a single page" in Drupal 6 and wound up here. The code which takes up most of the page appears to be merely the re-print of the commons.inc file included with the download of Drupal.

I have been searching for many days and have not yet found a straight-forward answer to my question--which is so easily done in HTML or PHP.

If you know how to simply add a JavaScript file to a single Drupal I would be so grateful if you would share it. Note: Simply referring to the file as an include file does not work.

I would like to add the

I would like to add the following javascript to a page or custom block, can not figure out how.

<!-- iSpeech Player Code-->
<script type="text/javascript" src="http://www.ispeech.org/embed/280263/2215009?autostart=no"></script><noscript><embed src="http://www.ispeech.org/ispeech.swf" quality="high" flashvars="autostart=no&playlist=http://www.ispeech.org/downloads/280263/2215009/audio.xml" type="application/x-shockwave-flash" width="204" height="35" pluginspage="http://www.macromedia.com/go/getflashplayer"><a href="http://www.ispeech.org/">Free Text to Speech</a></noscript>
<!-- iSpeech Player Code End -->

You can add in your theme

You can add in your theme (http://drupal.org/node/171205#scripts) or use drupal_add_js (http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_ad...) if you wish to add it in a custom module

*Return* JS instead of adding

Would it be possible to return the resulting JS code instead of adding it to the page?
It would be useful to assign it to a variable, like:

<?php
$theCode
= drupal_add_js("$('#link-newpass').insertAfter('#edit-pass-wrapper');","return");
// ...many lines later
print $theCode;
?>

Maybe there is a scope setting that can be used for this already?

Use the type "Inline" for

Use the "type" = "Inline" for that kind of stuff.

Run JavaScript after page loads

Many people may also wish to run some javascript just after the page loads. You could use code similar to the following.

In your php use a line like this (replace elements as appropriate):

drupal_add_js(drupal_get_path('module', 'your_module_name').'/run_after_page_loads.js', 'module');

In the run_after_page_loads.js file add code like this:

Drupal.behaviors.run_after_page_loads = function (context) {
    // Some jQuery that runs once the page loads.
    $('#hide_me').hide();
}

More technical and indepth description along with passing data from PHP to javascript here:
http://www.nicklewis.org/drupal-hackers-cookbook/jquery-js/unlocking-dru...

Using null

"If the first parameter is NULL, the JavaScript array that has been built so far for $scope is returned."

Note than the array build so far is also deleted!

Login or register to post comments