James Billings
James Billings

Reputation: 448

Loading images / links with jQuery & AJAX

I've been having trouble getting my images to show on the page after they have fully loaded through ajax. I did some research and solved the problem like this:

var img = $('<img id="img-photo-1" />').attr('src', data+'.png').load(function(){
                $("#jacket").html(img);
            });

Which is great, but I also want to wrap the image with a link also returned from AJAX so I tried this:

 img1 = $('<img id="img-photo-1 />').attr('src', data).load(function(){ 
           $("div#photo1").html('<a class="shadowbox" id="link-photo-1" href="'+data+'">'+img1+'</a>');
        });

But this shows the image as an object and doesn't render as an image. Any ideas on how to fix this, I'm sure it can be done with a similar approach, cheers

Upvotes: 0

Views: 294

Answers (2)

gen_Eric
gen_Eric

Reputation: 227270

Since img1 is a jQuery object, you can't use it like a string. Try using append to add it to the DOM.

img1 = $('<img id="img-photo-1 />').attr('src', data).load(function(){ 
    var $html = $('<a class="shadowbox" id="link-photo-1" href="'+data+'" />');
    $html.append(img1);
    $("div#photo1").empty().append($html); // I used empty(), because html() would replace anything inside the div
});

Upvotes: 1

fehays
fehays

Reputation: 3167

Your img1 var is a jquery element. So perhaps what you need is to return img1.html() to concatenate the anchor tag string you are building:

img1 = $('<img id="img-photo-1 />').attr('src', data).load(function(){ 
           $("div#photo1").html('<a class="shadowbox" id="link-photo-1" href="'+data+'">'+img1.html()+'</a>');
        });

Upvotes: 0

Related Questions