3

So I am injecting html via an AJAX request:

Ajax Response

  <div id="my-element">HTML from AJAX request</div>

The problem is that the element with id #my-element comes in from the AJAX request, but I need to bind events too it. For example:

 $(document).ready(function() {
    $("#my-element").click(function() {
        alert("hit");
    });
 });

Obviously the event above never fires, because when the page is ready, the HTML has not been injected from the AJAX request yet. What is the best solution to fix this?

Thanks.

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
Justin
  • 42,716
  • 77
  • 201
  • 296

4 Answers4

7

Try to use jQuery.on function: http://api.jquery.com/on/

$(document).on('click', '#my-element', function () { ... });

Then it will work even with dinamically added elements.

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
0

Add your event after injecting html via an AJAX request has been completed
or
you can use on method

see this example also

Event binding on dynamically created elements?

Community
  • 1
  • 1
rahul
  • 7,573
  • 7
  • 39
  • 53
  • But then I have to manage the events, because everytime the AJAX request is fired, it is going to bind another event. I.E. the AJAX request gets called every 10 seconds. – Justin Sep 01 '12 at 04:34
0

Use the on method to make it live.

$(function(){
    $("#my-element").on("click",function() {
        alert("hit");
    });
});
Shankar Cabus
  • 9,302
  • 7
  • 33
  • 43
-1

Do the binding in the success callback of your ajax call, after you ahve inserted the html into the DOM.

Lucas Green
  • 3,951
  • 22
  • 27