views:

32

answers:

2

I've got portions of pages being replaced with HTML retrieved via AJAX calls. Some of the HTML coming back has JavaScript that needs to be run once in order to initialize the accompanying HTML (setting up event handlers).

Since the document has already been loaded, when I replace chunks of HTML using jQuery's .html function, having jQuery(document).ready(function() {...}); doesn't execute since the page loaded long before and this is just a snippet of HTML being replaced.

What's the best way to attach event handlers whose code is packaged along with the HTML it's interested in, when that content is loaded via AJAX? Should I just put a procedural block of javascript after the HTML , so that when I insert the new HTML block, jQuery will execute the javascript immediately? Is the HTML definitely in the DOM and ready to be acted upon by JavaScript which is in the same .html call?

A: 

jQuery.live is there for this situation.

x1a4
+3  A: 

Some events can be bound to current and future elements using .live() http://api.jquery.com/live/:

$('.button').live('click', function() {
  // do something.
});

.live() does have some limitations (see linked documentation):

  • It does not work on native DOM elements so $('table').live('click', function(){}); won't work.
  • It cannot be chained like $('.somediv').next().live('click', function(){}); won't work.

The .delegate() method is supposed to alleviate these limitations but I understand it has limitations of its own. I have actually not used this one yet...haven't needed to. From the documentation:

Delegate is an alternative to using the .live() method, allowing for each binding of event delegation to specific DOM elements.

You can also bind new events in the AJAX success/error/complete functions in JQuery:

$.ajax({
  url: 'something.html',
  success: function(data) {
    //add new elements with data.
    //bind new events to elements
  }
});
Bradley Mountford