Grammin Grammin - 5 months ago 19
jQuery Question

How to call a function after a div is ready?

I have the following in my javascript file:

var divId = "divIDer";

jQuery(divId).ready(function() {
createGrid(); //Adds a grid to the html
});


The html looks something like:

<div id="divIDer"><div>


But sometimes my createGrid() function gets called before my divIder is actually loaded onto the page. So then when I try to render my grid it can't find the proper div to point to and doesn't ever render. How can I call a function after my div is completely ready to be used?

Edit:

I'm loading in the div using Extjs:

var tpl = new Ext.XTemplate(
'<div id="{divId}"></div>');

tpl.apply({

});

Answer

You can use recursion here to do this. For example:

jQuery(document).ready(function() {
  checkContainer();
});

function checkContainer () {
  if($('#divIDer').is(':visible'))){ //if the container is visible on the page
    createGrid();  //Adds a grid to the html
  } else {
    setTimeout(checkContainer, 50); //wait 50 ms, then try again
  }
}

Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid() function. If not, it will wait 50ms and try again.

Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)

Comments