Baehr Baehr - 5 months ago 31
Javascript Question

Javascript call function once loop finishes and jQuery populates content

I'm trying to get my jQuery to work in this flow:


  1. Parse json using $getJson

  2. Loop through returned JSON and create divs for each JSON item

  3. Once done, repeat but instead with another json file and append the results to the existing results.



But as of now I can't call another function AFTER the first loop is done, because the function gets called before the page is populated. How can I finish the populating loop, and then call another function?

I appreciate any help you can give me. Still learning as you can tell.

function test() {
var i;
for(i=0;i<=10;i++) {
$("div#test").append("<div id='"+i+"'></div>");
}
when_loop_is_done();
}
function when_loop_is_done() {
var i;
for(i=0;i<=10;i++) {
$("div#test div#"+i).append("<span>foo</span>");
}
}


Essentially I'm grabbing JSON from a separate page on my server, then looping through and populating the content using variables from that JSON object. The issue is no matter what I do, the second function always gets called before jQuery populates the content. So if I were to call an alert after the loop is done the page would pop up the alert and then load in all of the appended html.

Answer

Store your results in a variable or property. Then, use $(document).ready(fn) to wait for the page to finish loading and populate the page or finish your work when it has finished loading.