2

I'm using this piece of code inside of a for loop to append some content to a div:

$.get("./" + i + "/block.html", function(data){ 
    $(data).appendTo("#id");
});

After that, I'm using this piece of code to make the added content clickable, there's a .person div inside every block.html:

$(".person").click(function () { 
    $(this).toggleClass("large");
});

This second piece of code has no effect because the first piece runs asynchronously. So the content hasn't been appended yet by the time it runs. How can I delay it until it has been?

Cedric
  • 245
  • 1
  • 12

2 Answers2

1

One way of doing it is with a counter and if all data is loaded add it, this also ensures the data is added in the right order. The keyword let (instead of var) is very important, otherwise you have to use closures to capture the current value of i.

function addData(n) {
    let count = 0, content = []
    for (let i = 0; i < n; i++) {
        $.get("./" + i + "/block.html", function(data) { 
            content[i] = data // using var i would be n here
            if (++count == n) {
                for (let j = 0; j < n; j++)
                    $(content[j]).appendTo("#id")
                $(".person").click(function () { 
                    $(this).toggleClass("large")
                })
            }
        })
    }
}
maraca
  • 8,468
  • 3
  • 23
  • 45
0

I wanted to add a simpler solution I found.

You can run

jQuery.ajaxSetup({async:false});

at the start to make the get() functions run synchronously. If you need them to run asynchronously for another part of the page, just run

jQuery.ajaxSetup({async:true});

to switch back to asynchronous mode afterward.

Source

Cedric
  • 245
  • 1
  • 12
  • The reason I didn't mention that is: As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done(). But maybe I didn't understand this correctly and it is still usable if you don't use the jqXHR object? I don't know. Anyway the main difference is that this doesn't make the requests in parallel but sequential. – maraca Feb 18 '22 at 15:07