David
David

Reputation: 4895

Are element added by .append() already ready after appended?

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 ?

Upvotes: 0

Views: 122

Answers (3)

talemyn
talemyn

Reputation: 7960

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.

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

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);

Upvotes: 2

Matt Pileggi
Matt Pileggi

Reputation: 7196

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);

Upvotes: 4

Related Questions