Cheesetoast » icon http://www.cheesetoast.co.uk Brain Food for Web Developers Mon, 07 Jul 2014 23:18:22 +0000 en-US hourly 1 http://wordpress.org/?v=4.2.10 Add Icon for External Links with JQuery http://www.cheesetoast.co.uk/add-icon-for-external-links/ http://www.cheesetoast.co.uk/add-icon-for-external-links/#comments Thu, 01 Jul 2010 22:52:25 +0000 http://www.cheesetoast.co.uk/cheesepress/?p=24 This is a very basic JQuery tip that demonstrates how you can add an 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. Continue reading

The post Add Icon for External Links with JQuery appeared first on Cheesetoast.

]]>

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.

 

The post Add Icon for External Links with JQuery appeared first on Cheesetoast.

]]>
http://www.cheesetoast.co.uk/add-icon-for-external-links/feed/ 0