background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

How to open all external links in a new window using jQuery

Eric.London's picture

This quick code snippet will show you how to update every external link on your site to open in a new window using jQuery. You can put this code in the script.js file in your theme.

$(document).ready(function(){

  // apply to all <a> tags that have an href that starts with "http"
  $("a[href^='http']").each(function(){

    // remove http:// and https://
    link = $(this).attr('href');
    if (link.substring(0,7)=='http://') {
      link = link.substring(7);
    } else if (link.substring(0,8)=='https://') {
      link = link.substring(8);
    } else {
      return;
    }

    // spilt on '/'
    split1 = link.split('/');

    // compare href hostname to site hostname
    if (split1[0]!=location.hostname) {
      // add target attribute to link
      $(this).attr('target','_blank');
    }

  });

});

Use ext-link

There is a module extlink that does the same thing...

Eric.London's picture

thanks

Thanks for sharing. On my blog, I try to explain how things work under the hood of Drupal. -Eric

Compact this baby down!

Hey Eric,

Happened to come across this and thought it was great. After a little messing around I happened to get it compacted down to a couple of lines, tested it and it works so have a look:

$(function(){
$("a[href^='http']").each(function(){
var re_matches = /https?:\/\/([^\/]*)/.exec($(this).attr('href'));
if(re_matches[1] && re_matches[1] != location.hostname){
$(this).attr('target', '_blank');
}
});
});

Btw, please change your comment settings.. Having to preview your comment makes you put in a CAPTCHA twice.

it seems better to write:


$(function(){
$("a[href^='http']:not([href^='http://'+window.location.hostname.toLowerCase()])").attr({
target: "_blank",
title: $(this).attr('title')+" - this link will be open in a new window"
}).append(' [^]');
});

you sir, are the man! Keep

you sir, are the man! Keep up the good work!

Eric.London's picture

thanks

heh, thanks :)