tags:

views:

26

answers:

2

I want to make my images as links with help of jQuery:

 $("img:gt(0)").each(function () {
            var curr = $(this);
            if (curr.width() >= 500) {
                var m = 500 / curr.width();
                curr.height(curr.height() * m);
                curr.width(curr.width() * m);
            }
            $("<a href='" + curr.attr("src") + "'>").insertBefore(curr);
            $("</a>").insertAfter(curr);
        });

But I'm getting:

<a href="/Images/7827-1280x800.jpg"></a>
<img height="800" width="1280" src="/Images/7827-1280x800.jpg" alt="" style="height: 312.5px; width: 500px;">

Instead of:

<a href="/Images/7827-1280x800.jpg">
<img height="800" width="1280" src="/Images/7827-1280x800.jpg" alt="" style="height: 312.5px; width: 500px;">
</a>
+2  A: 

You don't have to do like this. You can use wrap to do this.

Something like

curr.wrap("<a href='" + curr.attr("src") + "' />");
rahul
Thank you. It works.
ieaglle
+1  A: 

You could use the wrap() method provided by jQuery

$("img:gt(0)").each(function () {
    var curr = $(this);
    if (curr.width() >= 500) {
        var m = 500 / curr.width();
        curr.height(curr.height() * m);
        curr.width(curr.width() * m);
    }
    curr.wrap($('<a href="' + curr.attr("src") + '">'));
});
Daniel