Why do I need to use .live() in Drupal Behaviors? I am trying to be a good boy and use Drupal Behaviors to manage my JavaScript. My understanding is that one of the advantages of using Behaviors is that it frees you from having to use .live() to bind event handlers to dynamically created elements. However, I find that I have to use .live() all the time. What am I doing wrong?

Here is a simple example of what I'm talking about:

Drupal.behaviors.MySearch = {

  attach: function (context, settings) {

    var searchBox = $('#my-search-box');
    searchBox.append("&lt;input type='text'&gt;&lt;/input&gt;");
    searchBox.append("&lt;button&gt;Search&lt;/button&gt;");

    $('#my-search-box button').click(function(){
      console.log("This does not work.");
    });

    $('#my-search-box button').live('click', function(){
      console.log("This does work.");
    });

};
My understanding is that one of the advantages of using Behaviors is that it frees you from having to use .live() to bind event handlers to dynamically created elements.


Yes and no. It certainly can be used for that, but it will only work if Drupal has invoked the previous AJAX call. If you've just done a $.ajax(...), Drupal won't know about it, and attachBehaviors() won't be invoked.

I would guess that your attach() method is indeed only being invoked once, as it would explain perfectly why the click handler is assigned once (when the page is first loaded), but not again. The live() will always work no matter how many times your attach() method is called.

If that is the problem, to fix simply add this to your AJAX success callback:

Drupal.attachBehaviors();