jQuery and ASP.NET

June 22, 2010

Create a Hyperlink of an Image using jQuery




Here’s a quick and easy way to create a Hyperlink of an Image using jQuery. Let us say you have the following image tags on the page:

<img alt="" src="http://www.dotnetcurry.com/Images/linq.gif" />
<
img alt="" src="http://www.dotnetcurry.com/images/Question.gif" />

To convert these images to hyperlink, we will use the jQuery wrap() function as shown below:

<script type="text/javascript">
$(function ()
{
$("#replAll").click(function ()
{
$('img').each(function ()
{
var currImg = $(this); // cache the selector
currImg.wrap("<a href='" + currImg.attr("src") + "' />");
});
});
});
</script>

What happens here is whenever the user clicks on the button, the wrap function wraps the anchor HTML structure around each image. After you click the button, you will observe that the images have become ‘clickable’, since they are now hyperlinks.

See a Live Demo



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Create a Hyperlink of an Image using jQuery"
  1. Anonymous said...
    June 22, 2010 11:33 AM

    $("img").click(function(){ window.location.href = $(this).attr("src"); });


    This does the same, and more importantly, it doesnt alter the html structure of your page, which could easily break your styling with things like floating images or image blocks.

  2. Orange Crush said...
    September 15, 2011 8:41 AM

    Thank you Anonymous, this method worked perfectly for me!

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions