Open External Links in a New Tab

This javascript snippet is in almost every site I build. It scans the links on the page and add target=’_blank’ to any anchor tag with a href not starting with our domain. Here are two different ways to do it using two different JavaScript libraries.

jQuery:

1
2
3
4
5
6
$("a[href^='http://']").each(function(){
    var thehref = $(this).attr('href');
    if(!thehref.match(window.location.host)){
        $(this).attr('target', '_blank');
    }
});

mootools:

1
2
3
4
5
6
$$('a[href^="http://"]').each(function(a) {
   var href = a.get('href');
   if(!href.contains(window.location.host)) {
      a.setProperty('target', '_blank');
   }
 });

Comments are closed.