Add handler to Ajax loaded content

Add handler to Ajax loaded content

Hi all,

I'm trying to bind an event handler to a button in a page loaded via Ajax. This procedure should apply to every page I have to load via Ajax. I have tried two things: first, I declared the 'click' event handler for the button like this, and just did my ajax request. Here's the code:

  1. $("#close_button").click(function(){
  2. alert("This should popup");
  3. });
  1. $.ajax({
  2. url: 'js/ajax/text.html',
  3. success: function (html){
  4. $(childDivSelector).html(html);
  5. },
  6. error: function (request, status){
  7. alert("Error loading:" + request.responseText);
  8. }
  9. });
The content loads a button with id #close_overlay, and thought that would work, but that was not the case. So my next attempt was to declare the 'click' event handler in the definition of the 'success' function, like this:

  1. $.ajax({
  2. url: 'js/ajax/text.html',
  3. success: function (html){
  4. $("#close_button", html).click(function(){
  5. alert("This should popup");
  6. });
  7. $(childDivSelector).html(html);
  8. },
  9. error: function (request, status){
  10. alert("Error loading:" + request.responseText);
  11. }
  12. });
Yet again, that doesn't work. I have found a similar question in Stackoverflow ( http://stackoverflow.com/questions/2124235/how-to-fire-event-handlers-after-ajax-content-has-loaded-in-jquery), but in my case I can't fire the event after the content has been loaded. The event should happen normally. 
There's a mention to the Livequery plugin, so I did another attempt:

  1. $("#close_overlay").livequery(function(){
  2. $(this).click(function(){
  3. alert("This should popup");
  4. });
  5. });
But that did not work either. Anyone has any thoughts on how to do this?
Thanks in advance and have a nice day