Drupal.attachBehaviors Simple Example

Javascript / JQuery / PHP / Ajax - Drupal 6

Update: 11/23/2011

This is a very popular topic, so I have decided to add a little more detail and hopefully clear up the process for some.
Visit the following links for a live example:

  1. Add custom Behaviors
  2. Attach behaviors to ajaxed content
  3. All together

An example module is attached below if anyone wants to take a closer look at the code.

This one was tricky:
While using javascript / jquery to call ajax functions backed by php I wanted to attach certain javascript behaviors to the new ajaxed content. In this case simply a resizable textarea in a form. This is how I got Drupal.attachBehaviors to work.

in the javascript file testing.js -> function testingBehaviors(action) { var url = '?q=testing/ajax/form/' + action; $('#test-form').load(url, function(){ Drupal.attachBehaviors(this); }); } in the php file testing.module -> function testing_init() { drupal_add_js(drupal_get_path('module', 'testing') . '/scripts/testing.js'); // will not work without the required js files loaded... drupal_add_js('misc/textarea.js'); }

The second step ensures that the required javascript files are loaded when the page is first loaded, before the ajax call.

Update:

Drupal links -

Download for Drupal 6: example module.