Drupal - Better understanding of Drupal behaviors

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:

  • Drupal behaviors
  • Drupal Javascript API
  • Changes in the Drupal JS API for D7

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.

Tags:

Javascript

7