58
  • What are Drupal behaviors at all?
  • What type of service layer it offers to module developers?
  • What type of relation it maps to jQuery.ready?
Thamilhan
  • 12,351
  • 5
  • 33
  • 59
Shoaib Nawaz
  • 2,152
  • 4
  • 28
  • 37
  • 1
    @JoshiConsultancy Generally speaking, an effective response on stackoverflow consists of a **direct answer** including links to citations and references. Most people who see this page **got here by searching** to begin with. – dreftymac Sep 26 '13 at 15:45

6 Answers6

83

Long version: Drupal.behaviors is not simply a replacement for jQuery.ready since the latter only runs once (when DOM is ready for manipulation): behaviors can be fired multiple times during page execution and can be run whenever new DOM elements are inserted into the document.

Also, modules could override or extend an existing behavior (e.g. if one module has a behavior of adding a bounce effect on all links, a second module could replace the behavior by a different bounce effect).

Short version: it's more modular, though the documentation could be improved.


Also, starting in Drupal 7, settings defined using drupal_add_js (PHP) or in Drupal.settings.modulename (Javascript) are directly passed as second parameter (the first one being the context) to the behavior.

For example:

Drupal.behaviors.changeLinks = function(context, settings){
    if (!settings) settings = Drupal.settings.changeLinks;
    $("a", context).hover(function() {
        $(this).css('color', settings.color);
    });
};

And if one of your script (or another) creates new nodes, it could still have the behaviors applied to the new nodes without having to know what other modules are iinstalled:

var newNodes = $('<a href="#">Hello</a> <a href="#">World</a>').appendTo('#someDiv');

Drupal.attachBehaviors(newNodes);
wildpeaks
  • 6,918
  • 2
  • 25
  • 34
  • Just to note you need to wrap any use of $() within (function ($) {//code in here})(jQuery); (With current versions of Drupal 7) Official documentation on it here: https://www.drupal.org/node/756722#using-jquery – Edward G-Jones Jun 19 '14 at 12:10
  • The context is the chunk from the DOM that has been modified. Initially, it is the entire document. But for all subsequent calls, it will only be the new added or modified part. For example, if you use the Lightbox library to open something new in a Lightbox, then you will have a context that will match only the newly added things. That way, any jQuery search/match will happen in a limited smaller set of HTML elements instead of the entire document. Also, this prevents reprocessing already processed elements. It's recommended to use $(".a-thing", context) for efficiency whenever applicable. – asiby Jan 31 '18 at 22:57
7

Duplicated Functionality

Note that the Drupal.behaviors architecture duplicates functionality already in jQuery.

Also, as of this writing, there does not appear to be any documentation or case studies for Drupal.behaviors outside of Drupal itself; and the documentation within Drupal (as stated above) could benefit considerably from improvements. As of this writing, it appears that the primary detailed documentation is restricted-access for-fee only.

This means you may notice performance degredation, anomalies, and unexpected results not consistent with standard jQuery that are endemic to the Drupal.behaviors ecosystem.

Native jQuery Functionality

In contrast to Drupal.behaviors, the built-in functionality of the standard jQuery API is extensively documented including in-line demonstrations and examples. Moreover, there are numerous live examples freely available on sites such as jsfiddle.

The links in the see also section enumerate the jQuery api calls relevant to handling new DOM elements inserted into the document.

See also

dreftymac
  • 27,818
  • 25
  • 108
  • 169
  • "there does not appear to be any documentation" Sorry but that is just wrong. Simply search for "jquery Drupal.behaviors" and you'll have 85k+ results. Here are some on my first page: https://drupal.org/node/756722 http://blog.amazeelabs.com/de/comment/510193 http://drewish.com/2011/05/11/drupal-javascripting/ There is certainly room for improvement here but as it stands your answer is more FUD than helpful. – s.Daniel Nov 25 '13 at 13:38
  • 2
    //there does not appear to be any documentation or case studies for Drupal.behaviors ***outside of Drupal itself***// (emphasis not in original) Please feel free to add any legitimate clarifications or corrections, but the assertion you made here is not accurate. Most importantly, you left out the words "outside of Drupal itself". If there are other frameworks or projects that have adopted Drupal.behaviors, please feel free to add links here and improve the quality of the answer. As it stands now, the addition does not refute anything in the original answer. – dreftymac Nov 25 '13 at 20:37
  • Behaviors are Drupal specific and that's why there is no documentation or use-cases outside Drupal. Behaviors expand jQuery functionality, they are not duplicating it. Sending context and settings is not something that jQuery does. And they also provide integration with Drupal's AJAX framework. Saying that they duplicate jQuery demonstrates very little understanding of Drupal JavaScript API. – Luxian Nov 13 '17 at 12:55
  • **//Behaviors are Drupal specific and that's why there is no documentation or use-cases outside Drupal//** Behaviors are implemented in Javascript. Javascript is not Drupal-specific. **//Saying that they duplicate jQuery//** Please feel free to carefully re-read the answer. There are four specific aspects identified. Nothing in the answer states that all of jQuery is duplicated by Drupal Behaviors. **//demonstrates very little understanding of Drupal JavaScript API//** Again, please feel free to re-read. The answer is very specific, not about the entire Behaviors API. – dreftymac Nov 13 '17 at 14:51
  • http://api.jquery.com/live/ does not do do exactly what Drupal behaviours do. Without going into much details, how are you doing to handle the Drupal settings properly? Also, Drupal behaviours can be triggered on demand and not only when the matched elements appear on the page. – asiby Jan 31 '18 at 23:00
  • **//api.jquery.com/live does not do do exactly what Drupal behaviours do//** Please feel free to carefully re-read the answer. It is stated that Behaviors duplicates functionality already in jQuery, not the other way around. – dreftymac Jul 07 '18 at 13:08
6

Along with answers mentioned above on of the key things is you can pass data from php to javascript which is as follows

Passing values from PHP to Javascript with "Drupal.settings"

You can easily make variables from PHP available to Javascript on the front end with Drupal.settings using drupal_add_js() function

<?php
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
?>

or

<?php
$element['#attached']['js'][] = array(
  'type' => 'setting',
  'data' => array('myModule' => array('key' => 'value')),
);
?>

This will be available in Javascript as:

  if (Drupal.settings.myModule.key === 'value') {
    alert('Got it!');
  }
Sameer
  • 91
  • 1
  • 4
4

Looking for a similar answer and arrived here, still without clues. Finally found a little more explanation (and examples) from an article here: https://benmarshall.me/drupal-behaviors/

I am not the original author, so I can only quote some texts:

What are Drupal Behaviors?

In short, Drupal.behaviors is a more modular and better way to implement jQuery.ready. Unlike jQuery.ready which only runs once when the DOM is ready for manipulation, Drupal.behaviors can be ran multiple times during page execution. Even better, they can be ran whenever new DOM elements are inserted into the document (i.e. AJAX driven content).

Drupal.behaviors can also override or even extend an existing behavior. So for instance, if a module behavior adds a bounce effect on all links, another module could replace that behavior with a different bounce effect.

Another added bonus of Drupal.behaviors (starting in Drupal 7), is the ability to use the drupal_add_js (PHP) or Drupal.settings.modulename (JS) and pass settings as a second parameter (the first being the context) to the behavior.

th.sigit
  • 61
  • 3
2

Drupal has a ‘behaviors’ system to provide a modular and better way for attaching JavaScript functionality to place elements on a page. Drupal Behaviors allows you to override or extend the existing behavior. These Drupal behaviors are event triggered programs that get attached to the page elements to be changed. While behaviours can be attached to specific contents, multiple behaviours are also attached and can be ablazed multiple times for a quick remake.

JavaScript by attaching logic to Drupal.behaviors. Here is an example taken from that page:

Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    $('.example', context).click(function () {
      $(this).next('ul').toggle('show');
    });
  }
}

;

1

Drupal behaviors are used if your JavaScript needs to be executed on page load and after an AJAX request (some new elements added in your document/html).

Drupal.behaviors.yourmodulename = {
  attach: function (context, settings) {
     // Code to be run on page load, and
    // on ajax load added here
  }
};

yourmodulename: This is your namespace and should be unique. For example, this is typically the name of your module, but it isn't mandatory.

context: This is actually really really cool, on page load the context will contain the entire document and after an AJAX request will have all the newly loaded elements. This way you can treat content that is loaded in via AJAX differently than others.

settings: This contains information passed on to JavaScript via PHP, it is similar to accessing it via Drupal.settings.

khurrami
  • 21
  • 5