Blog

25 Latest Articles
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!

 

Filed under: Tips & Tricks

1 Comments

Carrieann, Monday, January 09, 2012 4:04 PM

Stay infromatvie, San Diego, yeah boy!

Post your thoughts

Name (required)

Email (required)

Website

CAPTCHA image
Enter the code shown above: