14

Is there a callback for the html() function or a way to check that it is finished. For example:

$("#some_div").html('something here');

if($("#some_div").html() == ''){
//do something here
}

I am setting the html of an element from a post. Sometimes it doesnt load so when it doesnt load I would like for it to do something, is this possible. The way I have it now it always does the other thing because it hasnt set the html by the time it checks that it has html.

4
  • There shouldn't even be a race condition here. Do you have more code you can show so we can reproduce the problem? Commented Nov 20, 2009 at 23:49
  • a race condition? The code is alot more complex than that but all this basically does is set the html from a post callback to the success event. so $.ajax({ success:function(){ //set the html here } }); however sometimes it fails to show the html so I just want to make it run the function again to show it, but I am going to limit it to trying only 3 times and if it fails then they are sol lol Commented Nov 21, 2009 at 0:03
  • After adding html with .html(), the DOM is not updated synchronously and that is why you can't call on the item in the same code execution. Commented May 10, 2014 at 20:13
  • Here's an example of the problem and a workflow around it. To see this run this code: $("#some_div").html('<div id="newDiv"/>'); console.log($("#newDiv").length); The length will be 0 because the element does not exist yet. So, use an interval as your callback: var myInterval = setInterval(function(){ if ($("#newDiv").length){ clearInterval(myInterval); MY_FUNCTION(); } },10);//run it every 10ms Commented May 10, 2014 at 20:23

4 Answers 4

18

html() is a synchronous operation. The actual updating of the DOM depends on what your html content is. If you have <img> or <iframe> tags, they will take time to load. The next statement following the html() should immediately see the new html contents.

Did you mean load() instead?

[Edit] Based on your comment, it is probably your $.ajax failing. Not html(). Try attaching a failure handler to ajax call and retry from there? Although, if your server side code silently fails with a 200 code, the failure event doesn't get called. In that case, you can validate the html value before you set it to the element.

Sign up to request clarification or add additional context in comments.

5 Comments

+1. Judging by ngreenwood6's comment on his own question, the ajax call is the problem.
there is no problem with the ajax call. it works perfectly fine I am watching it in firebug. just sometimes it completes and shows me the data in firebug but the data is not there. No I am no using load. I am posting to a php page which is then calling my database class that is then returning data from the database to the user.
BipedalShark I dont think you know what you are talking about...You were trying to get me to use an infinite loop and you removed your post.
In my defense, I did immediately state it was a cheap hack. I deleted it because the premise of your question is fishy. As Chetan Sastry points out, the html() method is synchronous. There's no need for a callback.
as I said the ajax is not failing. I added an error event to it and it never executed. Also when I look at the response in firebug it has the information.
6

Chetan Sastry's answer(the highest answer now) is not 100% correct.

$('#some_div').html('<div id="new_div">some content</div>'); // code 1    
$('#new_div').click(function(){ }); //code 2

I don't know why, but in some cases, code 2 will be executed before code 1 finishing. There is a short time less than 0 millisecond between code 1 and code 2. It should be some special executing orders in Javascript.

You have to use cballou's way(the floor answer =_=!) to solve the problem. e.g.

var sync = function(fn, millisec){
    var m = millisec ? millisec : 0; //in face, 0 is enough
    return setTimeout(fn,m);
};

$('#some_div').html('<div id="new_div">some content</div>'); // code 1    
var code2 = function(){
    $('#new_div').click(function(){ }); // run code 2, here
};

sync(code2);

Comments

1

The only way i found with live and callback,

$('p').live('click', function() {
    // delay dont work with html() // fcallback function
    $(this).parent('div').slideUp('slow', function() {
      // empty block
      $(this).html('');
       if($(this).html()==''){
         // function
         myFunction();
       }
    });
});

Comments

-3

Hopefully somebody has a better solution than myself. A quick workaround is to use setTimeout() to delay your next calls, giving your HTML block enough time to load (since the load time is so miniscule).

$('#some_div').html('<div>some content</div>');
// set timeout for 250 milliseconds
setTimeout(callbackFunction, 250);

function callbackFunction() {
    // do some cool sh*t
}

Note, however, that if you wanted to pass any variables to your function, you could do the following:

$('#some_div').html('<div>some content</div>');
// set timeout for 250 milliseconds
var myParam = 'value';
setTimeout(function() { callbackFunction(myParam); }, 250);

function callbackFunction(myParam) {
    // do some cool sh*t
    alert(myParam);
}

4 Comments

That wouldnt really work because if the post takes longer than the timeout that I set it will fail, but thanks for the help.
You should be setting the html within the POST callback. An ajax request was not in your initial question.
This is bad practice, because its not dynamically.
Yeah this IS actually a solution, i ran into the same issue where a function after append and html was getting run even though it was after. I had to do a millisecond timeout on the function. It obv isnt perfect but it will at least stop the second line after the inserting of html from running right away.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.