Adding an External Link Icon using Font Awesome and JQuery

Sometimes you need to add an icon to your external links to mark them out as different to your regular site links. This makes sense in terms of usability as it stops users becoming suprised that they are taken away from your site on clicking the link. I recently worked on a site where one of the links read ‘University’ and was an external link. On the surface of it that would be difficult for a human user to differentiate as being an external link.

It can be an absolute maintenance nightmare and lead to massive code bloating if you try to add an icon after every external link using your server side language or CSS. I’ve seen it a few times and it’s caused hours of wasted development time and effort. This is why I rely on a javascript based solution as then when a change happens it only occurs in a single place rather than a few. Don’t get me wrong, it can be done on the server side or in the CSS but it’s my preference to make the user’s browser do the work for this.

I achieve this using jQuery and Font awesome to add a little icon after all external links. In my main script file, inside the standard $(document).ready function I add the following:

 

<code>
/*
* InitExternal
* Initialise external links
*/
var comp = location.host;

$('a').each(function () {
  //Get the link
  var link = undefined === $(this).attr('href') ? '' : $(this).attr('href');
  if (link != '' &amp;&amp; link.indexOf(comp) &lt;= -1 &amp;&amp; link.length &gt; 0) {
    if ($(this).text().trim().length == 0 || link.indexOf('javascript(') &gt; -1) {
      return;
    }

    if (link.charAt(0) != '/' &amp;&amp; link.charAt(0) != '#') {
       $(this).append('&lt;i class="fa fa-external-link external-link"&gt;&lt;/i&gt;');
       $(this).attr('target', '_blank');
    }
  }
});
</code>

 

The code analyses each a tag and checks for an href, without this there’s no point in continuing for that item. It then looks for whether the link has any inner content or whether it’s meant to invoke a javaScript function, if these cases match then it ignores that link. It then checks for invalid starting characters such as ‘#’ or ‘/’ . Finally it can add the icon and set the target to blank to mark the link as external. There may be permutations on your site where this doesn’t quite work, one such case is when the a tag is empty but has been used as an image box with a background image. In that case you could add

<code>
if($(this).css('background-image')){
      return;
}
</code>

The output :
Exteral Link Icon

Leave a Reply