Drupal jQuery behaviors

Drupal jQuery behaviors

Submitted by Jitesh Doshi on Sun, 05/12/2013 - 14:49
Drupal jQuery Behaviors

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. So you have to do nothing to add jQuery to your app. But on top of it, you also don't have to attach onload event handlers in JavaScript. Instead you simply write "Drupal JS behaviors" which are JavaScript functions that get invoked when attached (document loaded) or detached (document unloaded).

Let's take a look at an example:

Let's assume you want to convert all the 'select' elements in a given page, or all pages, into jquery multiselect widgets. I assuming you already know the basics of creating a module. The module in my example below is called 'wfdemo'.

  1. In your module, write the PHP code to inject JavaScript into the HTML page.
    <?php
    drupal_add_library('system', 'ui.dialog'); // add dependency libraries to the page
    $form['#attached']['js'][] =  drupal_get_path('module', 'wfdemo') . '/jquery.multiselect.min.js'; // attach JS to form
    $form['#attached']['css'][] =  drupal_get_path('module', 'wfdemo') . '/jquery.multiselect.css'; // attach CSS to form
    $form['#attached']['js'][] =  drupal_get_path('module', 'wfdemo') . '/wfdemo.js';
    ?>
  2. Above, the jquery.multiselect.* file are third-party files. But the last one - wfdemo.js - is a custom one written by us. This file is the one where we place our own Drupal Behavior.
  3. A Drupal behavior is a JavaScript object created under Drupal.behaviors object. In the example below, we have named our behavior 'wfdemo_multiselect'. The name can be anything arbitrary, but has to be unique.
    (function($) {
      Drupal.behaviors.wfdemo_multiselect = {
        attach: function(context, settings) {
          $('select.multiselect', context).once('wfdemo-multiselect').multiselect({});
        }
      }
    })(jQuery);
  4. 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. In most cases, you don't have to implement the 'detach' method, unless you have some cleanup to do in JavaScript (which is rare).
  5. The two arguments to the behavior are - context and settings.
    1. Context is the DOM object to which the behavior is attached. This could be the form, the form element or often the 'document' object. Typically, you would apply your JavaScript behavior to the 'context' object or its children.
    2. Settings can be special JavaScript object supplied at the time of attachment, but most of the times it is same as Drupal.settings.
  6. So in the above example ...
    1. we take the context (which is our form component)
    2. search for 'select.multiselect' ("select" element with class "multiselect") under it
    3. convert it into a multiselect by calling 'multiselect' jQuery plugin on it.
    4. but we want to do it only once (in case the behavior code gets executed multiple times), therefore we wrap the plugin call in 'once'
  7. The whole code above is wrapped in an IIFE (immediately invoked function expression).

I hope that explains Drupal behaviors and the right way to use them.

Jitesh Doshi

Profile picture for user Jitesh Doshi
Managing Partner & CTO
  • A seasoned technology entrepreneur and enthusiast
  • A regular speaker at industry conferences and universities
  • Host and organizer of technology user groups
  • Active in management of non-profit organizations serving the local community
  • Leader and contributor for multiple open-source projects
  • Expert in cloud, application integration, web and mobile technologies
  • Author of open-source projects, including on Drupal.org - Popular Tags and PRLP.
  • Developed several highly successful software platforms and frameworks for clients