51

I read about Drupal behaviors today, and I tried writing the following code.

(function ($) {

  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      $('#mymodule_id', context).change(function () {
        alert('Handler for .change() called.');
      });
    }
  };

}(jQuery));
  • Is Drupal.behaviors.mymodule the namespace?
  • What are the context and settings parameters passed to the Drupal behavior?
  • Is this the equivalent of document.ready()?
  • Can I attach any number of functions?
  • Can I define JavaScript functions which will be called somewhere?
57

In short, the advantage of Behaviors over document.ready() is that they are automatically re-applied to any content loaded through AJAX. mymodule is your namespace, which needs to be unique. context is the part of the page for which this applies, for example a part of a form that has been updated with AJAX. You can attach multiple behaviors, but I think you need to use a unique name (mymodule) for each of those.

Have a look at the following resources for more information:

2

In easy words, Drupal.behaviors is a better way to implement jQuery.ready

Unlike jQuery.ready which only runs once when the DOM is ready, Drupal.behaviors can be ran multiple times during page execution.

For example, in views infinite scroll, more elements will be loaded when user clicks load more button, hence , DOM will change after initial load.

What if we want to add classes to the newly added elements? Here Drupal Behaviors come handy.

The behaviors will be executed on every request including AJAX requests.

Drupal will call attached behaviors when the DOM is loaded and also when it is changed by Ajax, passing in two arguments

context and settings

The first time Drupal.attachBehaviors() is called, the context variable contains the document object representing the DOM, but for the rest of the calls context will hold the affected piece of HTML.

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

Furthermore, modules may call Drupal.attachBehaviors() as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.