Drupal jQuery Behaviors
Explanation of Drupal JavaScript behaviors and how to properly attach JavaScript to HTML components.
In this article, I try to explain “Drupal Behaviors”. Drupal provides a very clean way of attaching JavaScript code to HTML components. It includes jQuery library with it.
A Drupal behavior is a JavaScript object created under Drupal.behaviors object:
(function($) {
Drupal.behaviors.wfdemo_multiselect = {
attach: function(context, settings) {
$('select.multiselect', context).once('wfdemo-multiselect').multiselect({});
}
}
})(jQuery);
Our behavior must contain an ‘attach’ method, and can also optionally contain a ‘detach’ method. As you can imagine, ‘attach’ is called when the behavior is activated, while ‘detach’ is called when it is de-activated.
The two arguments to the behavior are:
- context - The DOM object to which the behavior is attached
- settings - Special JavaScript object supplied at the time of attachment
The whole code above is wrapped in an IIFE (immediately invoked function expression).