10 October 2010

Add icons for external links using jQuery

A common feature used on Web 2.0 sites and wikis is the external link icon: . It's a really cool way to show users that the link they are about to click is an external link. We can easily achieve this using jQuery.

First, you'll need to download the latest jQuery library and include it in the <head> section of your website/blog.

Put a block element somewhere in your page and give it an id:

<div id="extLinks">
 <p><a href="http://www.google.co.in" target="_blank">Google</a></p>
 <p><a href="http://www.facebook.com" target="_blank">Facebook</a></p>
 <p><a href="http://www.twitter.com" target="_blank">Twitter</a></p>
</div>

Open a script tag, define a document ready handler:

<script type="text/javascript"> 
 $(document).ready(function(){ 
  $('#extLinks a').each(function(i){
   if(this.hostname && this.hostname !== location.hostname){
    var URL = this.href;
    $($(this).parent()).append(' <a href=" ' + URL + ' "><img src="/images/external.png" alt="External Link" border="0" /></a>');
   }
  });
 });
</script>

That's it. You're done!

No comments: