Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add a link to an image using jquery?

Tags:

jquery

 <li id ="pdf1"> <img id ="pfd1img" src="/Content/img/pdf.png"/>Catalogue</li>

script:

 $("#pdf1img").attr('href', '/Content/pdf/' + data.pdf1);

I'm trying to add a hyperlink to an image. I think I'm nearly there, but am I missing something?

like image 734
Beginner Avatar asked Dec 07 '11 15:12

Beginner


2 Answers

$("#pdf1img").wrap($('<a>',{
   href: '/Content/pdf/' + data.pdf1
}));

Try that ^^^

Image elements cannot be links, but they can be wrapped in anchor elements which are.

.wrap() in jQuery Docs

like image 171
Naftali Avatar answered Nov 23 '22 05:11

Naftali


img elements do not have href attributes. If you want the image to act as a link you have a couple of options. You could wrap the img in an a element:

$("#pdf1img").wrap("<a href='/Content/pdf/" + data.pdf1 + "'>");

Or you could bind a click event handler to the image and use window.location:

$("#pdf1img").click(function() {
    window.location.href = "/Content/pdf/" + data.pdf1;
});
like image 31
James Allardice Avatar answered Nov 23 '22 07:11

James Allardice