Michael Giovanni Pumo
Michael Giovanni Pumo

Reputation: 14774

jQuery - Array of image URL's prints incorrectly

I have an array of image URL's and I wish to load these, in order to get the proper dimensions and then do stuff with them / output as needed.

Here's my code for handling that (loops an array of image URL's):

for (var i = 0; i < data.IMAGES.length; i++) {

    var img = $("<img />").attr('src', data.IMAGES[i].url)
    .load(function() {

        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {

            console.log("Error");

        } else {

            // This does output, but not correctly...

            if ( this.width > 299 ) {
                cache.$shareImages.append('<div class="share-image">' + img + '</div>');
            }

        }

    });
}

jQuery seems to append the content, but does so in a way which is odd. Here's an example of the output generated:

<div class="share-image">[object Object]</div>

I want to output the img tag itself that was created dynamically.

Why is this happening and how to solve it?

Thanks, Mikey.

Upvotes: 1

Views: 255

Answers (2)

Blowsie
Blowsie

Reputation: 40535

You need to chain the .append(), append the image to the newly created div , and then append that to your target

$('<div class="share-image"></div>').append(this).appendTo(cache.$shareImages);

Working Example: http://jsfiddle.net/blowsie/UCx73/

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150030

You're doing a string concatenation with:

 '<div class="share-image">' + img + '</div>'

...so it basically does a toString() on img, producing [object Object].

Perhaps you could try:

$('<div class="share-image"></div>').append(this).appendTo(cache.$shareImages);

EDIT: Note that the .load() handlers will run asynchronously after the loop has finished, at which point the img variable will be set to whatever img element was created last in the loop. So within the load use this to refer to the particular img just loaded.

Upvotes: 2

Related Questions