2

I am making ajax requests which return elements in a table. That all works great and it displays properly. However, I notice that any elements that are appended to the table that contain something like so

<div id="myId">Some Text</div>

will not be bound by previous javascript methods that bind to the myId method like so:

$("#myID").click(function() { alert("HI!") };

It works well on anything loaded before ajax is called but if it's html populated by ajax then for some reason those tags don't realize that they should listening for clicks.

Anyone have any insight on this. I'm using JQuery for what it's worth

Matthew Stopa
  • 3,793
  • 6
  • 42
  • 51

3 Answers3

6

Use live, like this:

$("#myID").live('click', function() { alert("HI!"); });

live binds the handler for current and future elements; click only does it for current ones.

cambraca
  • 27,014
  • 16
  • 68
  • 99
  • 1
    The new way to do this is `.on()` as described at [jQuery](http://api.jquery.com/on/) and [this](http://stackoverflow.com/questions/9344306/jquery-click-doesnt-work-on-ajax-generated-content) question/answer here. – Cato Minor Mar 26 '17 at 03:13
2

Your problem comes from the fact that .click() only binds your handler to already existing elements that match the selector. You need to make use of .live() or .delegate(), which will bind your handler to elements that exist now, as well as in the future. For simplicity, let's go with .live():

$("#myID").live("click", function() {
  alert("Hi!"); 
});

"How does it work?" you might ask. Well, .live() actually binds your handler to the specified event to document. It then watches for the specified event as it bubbles up the DOM. When it reaches document, it checks to see where the event originated, if it originated from an element matching your selector, your handler fires.

.delegate() works in much the same fashion, except that it binds the handler to the element you specify to $(), and as a parameter, it takes a selector. It then watches for the event and when it bubbles up to the element specified in $(), it checks to see if the event originated from the element you specified as the first parameter, if it does, your handler fires.

Alex
  • 64,178
  • 48
  • 151
  • 180
0

Another way to accomplish this is to change it to

$(document).on('click', '#myID', function() { });

Connor Smyth
  • 317
  • 2
  • 8