Blog

25 Latest Articles

Entries for December 2011

14

Selecting outbound links with jQuery

Maps on Kindle has a great article about using jQuery to select all outbound links on your web site.  In a nutshell, it creates a new selector by comparing the url of the link to the domain of the current web page.  That allows you to do things like this:

$('a:external').css('color', '#F00');

Pretty cool, right?

Unfortunately, there was a small oversight in their code, which I hope to rectify here.

In the original source, the code didn't account for the www problem.  If the visitor is looking at www.this.com/page [with the www.], and a link on the page points to this.com/something [without the www.], the script will consider it an outbound link.

To fix this, I've added a small tweak:


$.expr[':'].external = function(obj){
   return !obj.href.match(/^mailto:/) &&
      (obj.hostname.replace(/^www\./i, '') != document.location.hostname.replace(/^www\./i, ''));
};

Just add this to your JavaScript inside the $(document).ready(...) and you're all set.

Enjoy!