I ran across a situation where the I wanted to load the content of a div (modal popup) using jQuery AJAX.
Done it hundreds of times so implementing the AJAX call to populate the content was no issue, however I now needed to include some custom JS just for the content of the popup. I could not bind to the events of the elements in the popup until after the content of the popup was loaded, so this meant I could not include the JS in the main JS file, or if I did, I would need to execute a function to bind to the events after the AJAX call was complete. (Example below)
When I looked at the data returned by the AJAX call, it looked fine. Some HTML, then a script tag that included the small piece of JS I needed.
Problem was that the JS was firing before the HTML was actually added to the DOM. (try it and you will see)
The core reason is that jQuery functions like .html() , .prepend and a few others will add the script tag separately (and what appears to be before) it actually adds the HTML content.
I know there are ways to accomplish this with rewriting the AJAX call to not use .html(data), but I needed a quick way to accomplish this without alot of code. Welcome back setTimeout(). Easiest way I found to accomplish the task quickly was to wrap the small piece of JS code I was adding in a setTimeout() function. IF you are loading a large amount of content, this may not work. you will need to test it.
Does not work for me
<div><input id="myButton" name="myButton" type="button" value="Click me" /></div> <script> $("#mybutton").on("click", function () { alert("Clicked"); }); </script>
Works for me
<div><input id="myButton" name="myButton" type="button" value="Click me" /></div> <script>
setTimeout(
$("#mybutton").on("click", function () { alert("Clicked"); }) , 1000 ); </script>