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.
Do the binding in the success callback of your ajax call, after you ahve inserted the html into the DOM.
Use the
on
method to make it live.Add your event after injecting html via an AJAX request has been completed
or
you can use
on
methodsee this example also
Event binding on dynamically created elements?
Try to use
jQuery.on
function: http://api.jquery.com/on/Then it will work even with dinamically added elements.