Hanpan
Hanpan

Reputation: 10251

jQuery - Wrapping a dynamically loaded image

I am trying to wrap a dynamically loaded image with a link tag:

        var img = new Image();
        slideData[slide].imgData = img; 
        $(img).load(function () {
            $(this).css('display','none');
            $(this).wrap("<a></a>");
            slidesLoaded++;
        }).attr({src:mediaURL+slideData[slide].image, alt:slideData[slide].title});

This doesn't seem to work? When I do this:

$(slideData[0].imgData).appendTo('body').fadeIn()

There are no a tags, just the image.

Is this possible?

Upvotes: 1

Views: 185

Answers (2)

nickf
nickf

Reputation: 546243

When you wrap an element, that doesn't change the elements you have in your jQuery set.

Also, when you insert an element somewhere in the document (using .append, .prepend, etc), then that removes the element from its current position and puts it where you said.

So what's happening is that you're putting your image inside an <a> tag and then immediately removing it again to put it in the body. The <a> tag is never appended to the body. Obviously, the solution is to append the <a> instead of the image.

$(img).load(function () {
    $("<a></a>")
        .append($(this).hide())
        .appendTo(document.body);
});

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263047

That's because you stored the <img> element in slideData[slide].imgData, not the wrapper <a> element. Try:

$(slideData[0].imgData.parentNode).appendTo('body').fadeIn();

Upvotes: 1

Related Questions