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
.load()
, but eventually I'll be converting to JSONP and I don't think .load()
supports that?.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.
jQuery Callback Functions JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function.
jQuery ready() Method The ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above. The ready() method specifies what happens when a ready event occurs.
The contents() method returns all direct children, including text and comment nodes, of the selected element. A text node is the actual text displayed by an element. This method is similar to the children() method, except that it returns text and comment nodes as well.
$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ). on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. // A $( document ).
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With