Drupal Behaviors: A Quick Introduction & How-to

I’m fairly new to Drupal myself and came across something called Drupal Behaviors when I was working over at BioWare Austin. A fellow Drupal developer whom was part of the team, Ivan Fuyivara, gave a presentation on what they were and how to use them. Being a complete greenhorn at Drupal then, I was a little foggy on the concept and didn’t really understand. Now with a year of Drupal dev under my belt, a better understanding on how to do things the ‘Drupal way’, and an opportunity to work on a re-theme project at Stratfor Global Intelligence, I had the opportunity to put this feature into practice.

Here’s a quick introduction on what Drupal Behaviors are and how to use them. Feel free to critique or tell me I’m completely wrong here… in no way am I claiming to be a Drupal expert. You can also read more (though not too much info) on Drupal.org.

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.

How to Use Drupal Behaviors…

It’s actually fairly simple, I picked it up in less than 5 minutes… after my understanding of how Drupal works improved.

To many developers out there, something like this will do familiar:

jQuery(document).ready(function($) {
  alert('Green eggs and grey steaks!');
});

or maybe:

$(function() {
  alert('Green eggs and grey steaks!');
});

Yes, the code above works and there’s nothing wrong with it… unless you want to conform to the ‘Drupal way‘. Also, the code above will only get ran once which would be fine in this case, but what if your content was loaded via AJAX and you wanted to apply a class to all h1 tags?

$(function() {
  $('h1').addClass('.smelly-beans');
});

This will work for the content that initially get’s loaded but won’t get applied to new content that get’s added to the page. This is where Drupal.behaviors come in handy. Behaviors will be executed on every request including AJAX requests! Taking the example above, we’ve transformed it to use Drupal.behaviors:

Drupal.behaviors.makeMeSmelly = {
  attach: function (context, settings) {
     $('h1').addClass('.smelly-beans');
  }
}

Let’s break down that code:

  • makeMeSmelly: This is your namespace and should be unique. Typically it’s the name of your module, but isn’t mandatory.
  • context: On page load, the context will contain the entire document and after an AJAX request will have all the newly loaded elements. With this, you can treat content loaded by AJAX differently than what’s initially rendered.
  • settings: This contains information passed on to JavaScript via PHP, it is similar to accessing it via Drupal.settings. For further comprehension I recommend this source.

I don’t want my code ran on every request!

No problem, using jQuery once (integrated into D7 core) you can tell it to run only… you guessed it, once! See below:

Drupal.behaviors.makeMeSmelly = {
  attach: function (context, settings) {
    // This will only get ran once
    context.once(function() {
      $('h1', this).addClass('.the-original-smelly-bean');
    }
    
    // This get's ran on every request
    $('h1').addClass('.smelly-beans');
  }
}

The code above will add the class the-original-smelly-bean on all h1 tags that are initially rendered on the document. The smelly-beans class will get applied to all h1 tags regardless of when their loaded in the document.

If one of your scripts (or another) creates a new node, you can still apply the behaviors without knowing what modules are installed by using Drupal.attachBehaviors():

var newNodes = $('<a href="#">Smelly</a> <a href="#">Beans</a>').appendTo('#grey-steaks');
Drupal.attachBehaviors(newNodes);

Pass Local Settings to Drupal Behaviors

Another powerful feature of Drupal.Behaviors is the ability to pass local settings. This is a new addition to Drupal 7 and simple to use. See the example below taken from Drupal.org:

Drupal.behaviors.tableSelect = {
  attach: function(context, settings) {
    $('#example', context).html(settings.myvar);
  } 
};

That’s it! Pretty simple stuff huh? I’d love to hear any feedback you’ve got.

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

3 thoughts on “Drupal Behaviors: A Quick Introduction & How-to”

Leave a Reply

Your email address will not be published. Required fields are marked *