Search code examples
ajaxjquerydelegation

jQuery's delegate() does not bind events for AJAX loaded content


I want to use jQuery's .delegate() method as I've read it performs much better than .live().

However, when I use .delegate() it doesn't bind events to the ajax loaded content.

Can anyone help me get .delegate() working? Or am I stuck using the slower .live() for ajax loaded content?

   var randomObject = {

     'config' : {
       'form' : '#someform',
       'select' : '#someselect',
       'container' : '#pagecontainer'
     },


     'init' : function() {  

        randomObject.formEffects();
        randomObject.ajaxFormSubmit();    
    },


     'formEffects' : function() {

        ////////////// DELEGATE WON'T WORK on AJAX loaded content!
        //$('randomObject.config.form).delegate('select', 'change', function() {
        $(randomObject.config.select).live('change', function() {
           $(this).closest('form').trigger('submit');
        });
     },


     'ajaxFormSubmit' : function($form) { 

        $(randomObject.config.container).load($form.attr('action')+' '+randomObject.config.container, $form.data('form_values'), function(response, status, xhr){
           alert('updated!');
        });
     }, 

  };

Solution

  • Can't comment yet as I don't have permission. But with delegate, you need to bind the event above the content that is refreshed via AJAX. So if you're only reloading part of a page, don't set the delegate on content that is part of that page

    <script>
     $('#parent').delegate("a", "click", function(){
       // AJAX CODE replaces the contents of #parent but not parent itself
    });
    </script>
    <div id="parent">
          <div id="ajax">
              <a href="#">example</a>
              <p>Some content</p>
          </div>
    </div>
    

    I think in the case above this should work as the delegate is bound on #parent and #parent is not being updated. Obviously this is all pseudo code, but are you reloading the item that you delegate from? If so I think you would need to rebind the events. I'm pretty sure 'live' events get bound to the document and it then just compares the target to make sure it matches the selector. Delegate starts at the selector you specify so the event doesn't need to bubble up as far. (from what I understand)