Last updated October 27, 2015. Created on September 5, 2008.
Edited by milodescNickWildenod_digitaldonkeyLog in to edit this page.

See JavaScript API in Drupal 8 if developing for Drupal 8.

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.

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 (settingsbehaviorsthemes, 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 8for 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.

NoteDrupal 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. TheDrupal.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 6.x:

 

Drupal.behaviors.myModuleBehavior = function (context) {
  //Do some fancy stuff
};

Drupal 7.x:

 

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 theDrupal.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 allh3 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 theConverting 5.x modules to 6.x or Converting 6.x modules to 7.x page.

This usage is not in fact exclusive to Drupal 6: the jstools package in Drupal 5 used this exact pattern to control the behaviors of its modules: collapsiblock, tabs, jscalendar, etc.

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 6.x:

 

Drupal.behaviors.myModuleBehavior = function (context) {
  // 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 processed class (so that it will not
  // be processed again).
  $('.module-class-object:not(.module-class-processed)', context).each(function () {
    $(this).addClass('module-class-processed');
      // Do things.
  });
};

A real-live example is that in the OpenLayers module which uses this basic process to ensure that maps are only created once. It also utilizes Drupal behaviors to add parts and react to events.

Drupal 7.x:

 

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: The above example of the Drupal 7 version is just a rewrite of the D6 example here presented and may not represent the current version of the OpenLayers module code.

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 D7:

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.

Further information:

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

The way in which Drupal.behaviors works to trigger a document ready event didn't work in Drupal 7 for me:

 

Drupal.behaviors.myModuleBehavior = function (context) {
//do some fancy stuff
};

I had to implement it as such:

 

Drupal.behaviors.myModuleBehavior = {
        attach: function (context, settings) {
		//do some fancy stuff
	}
};

Hello,
I'm trying to make javascript with drupal but it's remaining one thing that i don't understand. It's the js object behaviors. I understood how implement it but i don't understand the goal of it. Please, is there somebody can explain it me ?
Thanks,
Fab.

i'm answering me, it could be helpful for people like me; the main advantage of using Drupal behaviors is that they are re-attachable, which becomes very useful when utilising AHAH/AJAX. Using '$(document).ready()' within 'script.js' means it will run only once (once the DOM is ready) each page load, whereas behaviors will be attached each time 'Drupal.attachBehaviors()' is called (and in Drupal 6 the 'drupal.js' file (/misc/drupal.js) is already set up to attach all behaviors for us upon intital page load).

In the first example, why is the Drupal Object being declared equal to itself?

Why could you not just use
var Drupal = { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };?

if the drupal object already exists it will not be overwritten with an empty version.. in your version it will be

What jadwigo said, but to explain a bit more: it's a shorthand for the ternary operator.

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

is effectively equivalent to

var Drupal = Drupal ? Drupal : { 'settings': ... }

It's a standard way of providing a variable default in Javascript.

--
J-P Stacey, software gardener, Magnetic Phield

One note about about the above code...

You probably don't want to define a local Drupal variable, otherwise your behaviors won't attach properly. So if you're adding your own behaviors, you'll want to refer to the global Drupal object, like this
Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };
instead of
var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

TL;DR: when defining your custom behaviors, drop the 'var'.

I've got a page with an unknown number of node teasers and need to be able to pass the right parameters to my onClick event for the currently-clicked node. I found plenty of docs for passing a single setting, but couldn't find much for passing an array and accessing the relevant item. Here's what worked for me:

 foreach ($nodes as $node) {
      // add data for the current node to the parameters list
      $location[$node->nid] = array(
         'nid' => $node->nid,
         'title' => $node->title
      );
      $list[] = '<div class="store" id="' . $node->nid . '"onClick=redrawMap()>' . render(node_view($node, 'teaser')) . '</div>';  // $list gets passed to my theme() function
    }
    // pass the location params array to js
    drupal_add_js(array('MYMODULE' => array('location' => $location)), 'setting');

Then, in javascript, I can get the parameter I need (e.g., title) for the currently-clicked node like so
    Drupal.behaviors.MYMODULE = {
        attach: function(context, settings) {
            $('.store').click(function() {
                var id = this.id;
                var title = settings.MYMODULE.location[id].title;
                // ...
            });
        }
    };

I apply the similar code in my case to pass a variable from module php to javascript as
in .module file
drupal_add_js(array('mymodule' => array('companyID' => $form_state['storage']['companyID'])), array('type' => 'setting'));

in js file
(function ($) {
$(document).ready(function() {
Drupal.behaviors.mymodule = {
attach: function (context, settings) {
var companyId = Drupal.settings.mymodule.companyID;
$('#' + companyId).addClass("active-row");
}
};
});
})(jQuery);

It works just the way I want except that all the validation message generate by form_set_error() disappear although the invalid input value fields are highlighted.

Further trace down to know what is the line of code causing this. Found out that this is the line
var companyId = Drupal.settings.mymodule.companyID;

As far as I comment this line, the validation error message appear again.

What should I do in order to fix this? Thank you so much

Great Its really helpful for me ..
Thanks ...!

If the document is passed as context, how is that even useful? You could remove the context in the above examples and get the same result. It's jQuery's .once() method that does the magic of only binding to non-modified elements.

Even if you load new content via ajax, you could bind those newly created elements within your AJAX response callback with no need for a context var.

So what's the point?

Hi AlxVallejo,

As behaviours are called on Ajax requests as well on document ready, context can just contain the elements that are newly added or modified etc.

This, I assume, makes for less intensive traversing of the Dom with selectors, and therefore far less CPU cycles on the client's machine.

You might want to execute a callback on various elements every time the 'context' changes, i.e. Ajax request completed, therefore, once() is not used.

At least, this is my best guess to its function.

Cheers.

This article clarified why using context and .once() was a best practice:http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behav...

Make sure to read the comments.

What exactly does once() do?
I see that it says, "Apply the myCustomBehaviour effect to the elements only once," but it's not clear what "myCustomBehaviour" is or what it means to "apply" it.

See http://drupalapi.attiks.com/api/drupal/misc!jquery.once.js/function/%24....for documentation.

Basically it takes the list of elements that match the selector in id, filters it to exclude any that have previously had the function given as the second argument executed on them, marks the ones that haven't, and then executes the function. It's mostly about preventing unnecessary javascript calls.


来自 https://www.drupal.org/node/304258