Shaun Mccran

My digital playground

27
J
U
L
2011

Simple JQuery way to detect links pointing to external domains

Ever wanted to detect links on your site that point to other domains? A few times in the past I've had requests to be able to pick out all the hyperlinks from a site that move a user to a different domain.

The code below checks starts with a click event on all anchor links. It then pulls out the hyperlink reference and checks whether it matches the current documents domain. If the destination of the link points to a different domain then you have a block of code that is performed when the user clicks on the link.

view plain print about
1$('a').click(function() {
2
3    var href = $(this).attr('href');
4
5if ((href.match(/^https?\:/i)) && (!href.match(document.domain)))
6 {
7    var extLink = href.replace(/^https?\:\/\//i, '');
8    alert('clicked external link');
9 }
10}

Pretty simple, but it allows you to amend the link with a custom message, or track it in any way you want.

TweetBacks
Comments
Back to top