Wednesday 19 September 2012

How to put link on image using jQuery

http://phpgyan.blogspot.inTo put link of the image, we normally use <a> tag that contains image tag to show the image. But assume there are 100 images and you need same link for every single image. Putting 100 <a> tag with each image is time consuming and cumbersome. It would be nice if single <a> tag can be used for all the images and put the <a> tag dynamically. Well, no worry when there is jQuery.

jQuery provides a method named "wrap()", which can be used to insert any HTML structure in set of matched elements. In simple words, if you want put wrapper around your div element then you can use wrap() method. For example, you have a div with ID "Child".
1<div id="Child"></div>
And want to wrap this div with any parent then you can use "wrap()" method to insert HTML.
1$('#Child').wrap('<div id="Parent"></div>');
Output:
1<div id="parent">
2  <div id="child"></div>
3</div>
Same way, we will use the wrap() method to insert hyperlink to image tag so that the image becomes clickable. See below.
1$(document).ready(function() {
2    $("#imgLogo").wrap('<a href="http://phpgyan.blogspot.in/"></a>');
3});
In this example, I have used ID as selector but you can use class selector to find all the images with same class and then wrap them with <a> tag. You can also assign target="_blank" in the above <a> tag to open the link in new window.
See live Demo and Code.

No comments:

Post a Comment