Graham Charles Graham Charles - 3 months ago 12
jQuery Question

does jquery.html() have a "ready" or "complete" callback?

I'm using DOM insertion to generate some data entry dialogs. I'm finding that in some browsers, particularly mobile browsers and IE-Mac, manipulations immediately after the

.html()
call don't fire, presumably because the modified DOM is not yet ready. For example:

$.ajax({
type: "GET",
url: url,
dataType: 'html',
success: function (data, textStatus, jqXHR) {
$("#theDialog").html(data);

// hide address
$("#theDialog #BillingAddress").closest("li").hide();
...


This works most of the time, but certain browsers sometimes fail to hide the indicated
<li>
. And it's been challenging to debug, because going to console seems to allow the browser to complete the DOM insertion, and so the
.hide()
always works when stepping through the code.

I suppose what I'm after is either a
$("#theDialog").on("ready")
or a callback from the
.html()
method. But those don't seem to exist.

I've thought of


  1. Switching to
    .load()
    , but eventually I'll be converting to JSONP and I don't think
    .load()
    supports that?

  2. Putting the
    .hide()
    and other DOM manipulation in a script tag within the returned data.



I suspect #2 is the recommended approach but wanted to do a sanity check here first. Has anyone experienced this?

Many thanks.

Answer

Although my previous answer worked, it didn't solve all your problems. I recommend something like:

var myDiv=document.createElement( 'div' );
myDiv.innerHTML=data;
// now do all of your initializing, passing in myDiv like $( myDiv )
$("#theDialog").html(myDiv.innerHTML)
  .find( '#BillingAddress' )
  .closest("li")
  .hide();

Hope this works!

Comments