How can I ensure that JavaScript inserted via AJAX will be executed after the accompanying HTML (als
Posted
by RenderIn
on Stack Overflow
See other posts from Stack Overflow
or by RenderIn
Published on 2010-05-14T16:23:12Z
Indexed on
2010/05/14
16:34 UTC
Read the original article
Hit count: 174
I've got portions of pages being replaced with HTML retrieved via AJAX calls. Some of the HTML coming back has JavaScript that needs to be run once in order to initialize the accompanying HTML (setting up event handlers).
Since the document has already been loaded, when I replace chunks of HTML using jQuery's .html
function, having jQuery(document).ready(function() {...});
doesn't execute since the page loaded long before and this is just a snippet of HTML being replaced.
What's the best way to attach event handlers whose code is packaged along with the HTML it's interested in, when that content is loaded via AJAX? Should I just put a procedural block of javascript after the HTML , so that when I insert the new HTML block, jQuery will execute the javascript immediately? Is the HTML definitely in the DOM and ready to be acted upon by JavaScript which is in the same .html
call?
© Stack Overflow or respective owner