JavaScript API overview

Last updated on
11 March 2021

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

This documentation needs work. See "Help improve this page" in the sidebar.

This page is a description of how JavaScript is implemented in Drupal, including an in-depth look at the drupal.js file and in particular the Drupal js object initialized therein.

A couple of simple principles guide Drupal's JavaScript approach:

  • All pages should be perfectly functional without scripts. JavaScript provides alternatives or supplements, not replacements, for standard elements.
  • No JavaScript is hard-coded into pages. Rather, actions are attached dynamically to page elements, and only if the needed JavaScript support is present.

Note: The following examples are lacking JSDoc, only for clarity.

The very first line of JavaScript code in Drupal core, in drupal.js, is an Object declaration:

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

In this code, Drupal is an Object declared to be equal to itself, or, if not yet set, equal to { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} } which is an Object containing 4 properties (settings, behaviors, themes, and locale) each of which is itself an Object. This line of code is an Object Initializer. This Drupal object and its properties can then be used and extended by other modules. The best way to understand this is to look at the different properties one by one and the ways they are used by Drupal modules.

Jump to a section:
Drupal.settings
Drupal.behaviors
Drupal.theme
Drupal.locale

Drupal.settings

Drupal.settings is what enables us to pass information from our PHP code to our JavaScript code. This means you can change how your JavaScript behaves based on your module. For example, you may want to simply let JavaScript know what the base path is. In order to do this, you just create a PHP array of settings, as follows:

$my_settings = array(
  'basePath' => $base_path,
  'animationEffect' => variable_get('effect', 'none')
 );

Note: The array keys are set using CamelCasing according to the JavaScript coding standards.
@see: https://drupal.org/node/172169#camelcasing

Then call drupal_add_js() and pass in this array, with "setting" as your second parameter:

drupal_add_js(array('myModule' => $my_settings), 'setting');

(Drupal 8 deprecates drupal_add_js; refer to Attaching Configurable JavaScript in Drupal 8 for the D8 way to pass values from PHP to JavaScript.)

Note that it is further padded inside another array purely for namespacing purposes: another module might define the basePath setting as well. Now you can access these settings in your JavaScript code as follows:

var basePath = Drupal.settings.myModule.basePath;
var effect = Drupal.settings.myModule.animationEffect;

These are strings, but not string objects in JavaScript. The value of the array key you pass into drupal_add_js() will be concatenated to the end of this string separated by a comma.

Note: Drupal 7 passes the settings locally

Drupal.behaviors

When most of us learn jQuery for the first time, we learn to put all our code inside the $(document).ready() function, like this:

$(document).ready(function () {
  // Do some fancy stuff.
});

This ensures that our code will get run as soon as the DOM has loaded, manipulating elements and binding behaviors to events as per our instructions. However, as of Drupal 6, we don't need to include the $(document).ready() function in our jQuery code at all. Instead we put all our code inside a function that we assign as a property of Drupal.behaviors. The Drupal.behaviors object is itself a property of the Drupal object, as explained above, and when we want our module to add new jQuery behaviors, we simply extend this object. The entire jQuery code for your module could be structured like this:

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    $('input.myCustomBehavior', context).once('myCustomBehavior', function () {
      // Apply the myCustomBehaviour effect to the elements only once.
    });
  }
};

@see: https://www.drupal.org/update/modules/6/7#jquery_once

Any function defined as a property of Drupal.behaviors will get called when the DOM has loaded. drupal.js has a $(document).ready() function which calls the Drupal.attachBehaviors() function, which in turn cycles through the Drupal.behaviors object calling every one of its properties, these all being functions declared by various modules as above, and passing in the document as the context.

The reason for doing it this way is that if your jQuery code makes AJAX calls which result in new DOM elements being added to the page, you might want your behaviors (e.g. hiding all h3 elements or whatever) to be attached to that new content as well. But since it didn't exist when the DOM was loaded and Drupal.attachBehaviors() ran, it doesn't have any behaviors attached. With the above set-up, though, all you need to do is call Drupal.behaviors.myModuleBehavior(newcontext), where newcontext would be the new, AJAX-delivered content, thus ensuring that the behaviors don't get attached to the whole document all over again. There are full instructions on how to use this code on the Converting 5.x modules to 6.x or Converting 6.x modules to 7.x page.

Drupal.behaviors practical example

The following is a more practical example. Drupal Behaviors are fired whenever attachBehaviors is called. The context variable that is passed in can often give you a better idea of what DOM element is being processed, but it is not a sure way to know if you are processing something again. Passing the context variable as the second argument to the jQuery selector is a good practice because then only the given context is searched and not the entire document. This becomes more important when attaching behaviors after an AJAX request. The following is an example of a Drupal.behavior that ensures that processing only happens once per DOM object.

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    // This jQuery code ensures that this element
    // is only processed once.  It is basically saying:
    // 1) Find all elements with this class, that do not
    // have the processed class on it
    // 2) Iterate through them 
    // 3) Add the myCustomBehavior-processed class (so that it will not
    // be processed again).
    $('input.myCustomBehavior', context).once('myCustomBehavior', function () {
      // Apply the myCustomBehaviour effect to the elements only once.
    });
  }
};

Note: Your included JS file needs to have the function($) prototype definition which is not mentioned above! So my WHOLE file would look like

(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
     $('input.myCustomBehavior', context).once('myCustomBehavior', function () {
      // Apply the myCustomBehaviour effect to the elements only once.
    });
    }
  };
})(jQuery);

Drupal.theme

Drupal.theme() is the client-side counterpart to the server-side theme() function. Here's what it looks like in Drupal 7:

Drupal.theme = function (func) {
  for (var i = 1, args = []; i < arguments.length; i++) {
    args.push(arguments[i]);
  }
  return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
};

So, when you make a call to Drupal.theme(), you pass in a function name as your first argument and all subsequent arguments will be arguments to be passed to that function. The function you pass in will need to be a member of Drupal.theme() object, an example of which is below:

Drupal.theme.myThemeFunction = function (left, top, width) {
  var myDiv = '<div  id="myDiv" style="left:'+ left +'px; top:'+ top +'px; width:'+ width +'px;">';
  myDiv += '</div>';
  return myDiv;
};

And here's how you would call it:

Drupal.theme('myThemeFunction', 50, 100, 500);

Drupal.locale

The Drupal.locale property works in conjunction with Drupal.t(), the JavaScript equivalent of the server-side t() function. It holds a collection of string translations so that Drupal.t() can then access the required string from Drupal.locale in order to translate what was passed into it.

Help improve this page

Page status: Needs work

You can: