0

I am building a kind of infinite scroll with jquery, but I am facing a DOM ready problem.

var n = 0;

// When user wants to load more, call this 
function load_10_images(){

    var g; var images = '';

    for(g=1; g<=10; g++){

        // Create images
        images = '<div id="'+n+'" >'+
                    '<li id="li'+n+'">'+
                        '<img id="img'+n+'" src="images/loading.gif" />'+
                    '</li>'+
                 '</div>';

        // add to html
        $("#list").append(images);

        // change source
        $.ajax({
            type: "POST",
            url: "data.php",
            data: {link_n: n},
            success: function(resp) {
                $("#img"+n).attr("src", resp);
            },
        });

        // ...
        n++;
    }

}

My problem is images sources don't change. How to solve this problem ?

David
  • 4,785
  • 7
  • 39
  • 63
  • `var n = g;` inside your loop? – Malk Feb 25 '14 at 21:06
  • I checked the response with alert(), and it gives me the wanted link ('http://example.com/images/1.png'), so the problem is not from my php file. – David Feb 25 '14 at 21:08
  • 1
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Barmar Feb 25 '14 at 21:09

3 Answers3

4

Your problem is scope. You create the DIVs and IMG ids with n as you loop through it. But you access the value of n in your ajax callback. So it will attempt to find $("#img"+n).attr("src", resp); with whatever the current value of n is (most likely the final value since it will finish faster than the post returns);

Matt Pileggi
  • 7,126
  • 4
  • 16
  • 18
2

The problem is that since AJAX is async, your variable n inside the success call is equal to the variable n inside the last loop. Add a closure like that :

(function(int){
    $.ajax({
        type: "POST",
        url: "data.php",
        data: {link_n: int},
        success: function(resp) {
            $("#img"+int).attr("src", resp);
        },
    });
})(n);
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
0

As many people have pointed out, you have other issues that are causing the problems that you are seeing, but to answer your actual question, yes, they are available after .append(). Actually, what you find people do, frequently, is actually make the element available before appending it. In your code (since you're using jQuery), you could do that like this:

images = $('<div id="'+n+'" >'+
    '<li id="li'+n+'">'+
        '<img id="img'+n+'" src="images/loading.gif" />'+
    '</li>'+
'</div>');

At that point, the element exists and can be read, modified, etc., but simply has not been added to the DOM yet.

talemyn
  • 7,822
  • 4
  • 31
  • 52