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.');

  • 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?
up vote 54 down vote accepted

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:

This blog post from Lullabot does a great job of explaining the concepts around JS behaviors: https://www.lullabot.com/articles/understanding-javascript-behaviors-in-drupal

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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