Add a favicon near external links with jQuery


Posted by liviuh on 22 September 2009

External links should always be marked distinctly in order to see them easily. First I thought adding a CSS class to all a[href^=http] will be more then fine. After that I got the better idea of using the favicon.ico of the external site, if it is available of course. Here is the code:

jQuery('a[href^="http://"]').filter(function(){
     return this.hostname && this.hostname !== location.hostname;
}).each(function() {
    var link = jQuery(this);
    var faviconURL =
      link.attr('href').replace(/^(http:\/\/[^\/]+).*$/, '$1')+'/favicon.ico';
    var faviconIMG = jQuery('<img src="favicon.png" alt="" />')['appendTo'](link);
    var extImg = new Image();
    extImg.src = faviconURL;
    if (extImg.complete)
      faviconIMG.attr('src', faviconURL);
    else
      extImg.onload = function() { faviconIMG.attr('src', faviconURL); };
});

You can download the FavoriteIcon plugin version (0.9kb) and use it in your project in your best interest:

$(document).ready(function() {
     $("a").favoriteIcon({ iconClass : 'favoriteIcon' });
});