Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for jquery .html method to finish rendering

I have div with vertical scroll bar. Div is being updated dynamically via ajax and html is inserted using jQuery's .html method. After div is updated scroll bar returns to top and I am trying to keep it in the previous position.

This is how I'm trying it:

var scrollPos = $('div#some_id').scrollTop(); //remember scroll pos
$.ajax({...
    success: function(data) {
        $('div#some_id').html(data.html_content); //insert html content
        $('div#some_id').scrollTop(scrollPos); //restore scroll pos
    }
});

This fails. My best guess is that it is failing due to inserted html not rendered (ie. no scroll).

For example this works.

setTimeout(function(){
    $('div#some_id').scrollTop(scrollPos);
}, 200);

But this is dirty hack in my opinion. I have no way of knowing that some browsers won't take more then these 200ms to render inserted content.

Is there a way to wait for browser to finish rendering inserted html before continuing ?

like image 752
Vladimir Cvetic Avatar asked May 20 '12 12:05

Vladimir Cvetic


2 Answers

I will just like to point out one difference here: One thing, is when the .html() have completed loading, but the browser actually render the content is something different. If the loaded content is somewhat complex, like tables, divs, css styling, images, etc - the rendering will complete somewhat later than all the dom ellements are present on the page. To check if everything is there, does not mean the rendering is complete. I have been looking for an answer to this by myself, as now I use the setTimeout function.

like image 130
olekeh Avatar answered Nov 16 '22 00:11

olekeh


It's still a hack, and there really is no callback available for when the HTML is actually inserted and ready, but you could check if the elements in html_content is inserted every 200ms to make sure they really are ready etc.

Check the last element in the HTML from the ajax call:

var timer = setInterval(function(){
   if ($("#lastElementFromAjaxID").length) {
       $('div#some_id').scrollTop(scrollPos);
       clearInterval(timer);
   }
}, 200);

For a more advanced option you could probably do something like this without the interval, and bind it to DOMnodeInserted, and check if the last element is inserted.

like image 9
adeneo Avatar answered Nov 15 '22 23:11

adeneo