Cheesetoast

Brain Food for Web Developers

JQuery Logo

Add Icon for External Links with JQuery

This is a very basic JQuery tip that demonstrates how you can add an icon (external link icon) to external anchor links. A similar approach is also useful is you want to add filetype icons to your links, such as pdf’s or txt files.

First of all, there are several ways this can be done. You could use CSS to create a class,

.external_link {
background: url(/images/external.png) center right no-repeat; padding-right: 10px; }

and manually add the class to each external link on your site. Of course this is something you can easily forget to do and is not very practical when you have content being generated dynamically. To get around this you might replace the class with a css selector that checks to see if each link starts with a ‘http://’, like so:

a[href^=”http://”] { … }

The problem there is that IE6 (oh joy) does not support this selector. Another issue crops up when you use absolute links to your own pages instead of relative ones (i.e. you use “http://www.yoursite.com/images/picture.jpg” instead of just “/images/picture.jpg”), in which case the absolute link would appear to be an external one.

Another way of doing this is to use JQuery to select all the links that point away from your site and automatically add the icon. You could potentially combine the two methods so that browsers with javascript disabled still get the benefit of the CSS method.

Here is the code for that:

$(document).ready(function() {
$(‘a’).filter(function() {
return this.hostname && location.hostname !== this.hostname;
}).addClass(‘external_link’);
});

The first line checks that the page is ready. The second line selects all anchors and applies the following filter to them. The filter checks that the location of the link does not match the current site AND checks that internal links such as ‘mailto’ are not included. If these conditions are met then it will add the CSS class mentioned previously.

 

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

Comments are closed.