jQuery snippet to force external links into a new window

Usability concerns aside, one thing that is often requested by clients is to force all outbound links from their website into a new window. Here's a little jQuery script I use that achieves just that:

(function($) {
  $(document).ready(function() {
    var hostname = window.location.hostname.toLowerCase();    
    $("a").each(function() {
      var href = this.href.toLowerCase();
      if (href.indexOf("http") === 0 && href.indexOf(hostname) === -1) {
        $(this).addClass('external').click(function(e) {
          e.preventDefault();
          window.open(href, '_blank');
        });
      }
    });
  });
})(jQuery);

The script also adds a class of external to each outbound link, allowing you to style them in some way that differentiates them from normal links. Using JavaScript (and jQuery) for this purpose, offers a few benefits:

  1. All outbound links are targeted in one fell swoop.
  2. Adding target="_blank" to links is invalid markup when using the XHTML Strict 1.0 doctype.