1

I've created a web page that populates the content of a div using an AJAX request.

I'm using

$('#div_id').html(data); 

to populate the div and this works fine.

However all of the returned content has lost its JQuery, no more onclick events and no JQueryUI widgets.

I've tried calling all of these

$('#div_id').trigger('create');
$('#div_id').html(data).trigger('create');
$('body').trigger('create');

and all the same with 'pagecreate' rather than create.

None of this is working although everything I've found whilst googling is related to JQuery Mobile so I could be completely barking up the wrong tree.

Thanks

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Luke
  • 109
  • 2
  • 12
  • 1
    You need to use [event delegation](http://learn.jquery.com/events/event-delegation/). – Ben Fortune Jun 23 '14 at 12:07
  • 2
    Because the elements are being appended after the DOM has loaded, you need to use delegated event handlers: `$(document).on('create', '#div_id', fn);` – Rory McCrossan Jun 23 '14 at 12:07

1 Answers1

0

You need to use event delegation when you append new elements to the DOM like that.

Hard to give an exact answer without seeing the HTML, but say you have a button that you're adding with an on click handler... You would attach the handler to the #div_id instead like this:

$('#div_id').on('click', 'button', function () {
  //do your thing...
});

The second argument in the on method is the element that will dispatch the event. You can think of it like an "if" statement. The handler is attached to the ancestor element and when the event bubbles up to it, the event is triggered. When it's triggered, that second argument is checked. It says "did 'button' dispatch this event?", if the answer is "yes" the function callback runs.

jme11
  • 17,134
  • 2
  • 38
  • 48