Javascript code: open external links in new window with override

Category: 

  • Tip / Idea

See https://drupalcloud.mit.edu/community/add-javascript for how to add Javascript to DC sites. Feel free to use/improve/alter as needed. See code comments for behavior specifics.

// Note: this Javascript block should have a higher weight (lower in sort order) than other Javascript blocks which add links to the page.
(function($) {

/**
* Finds all external links and opens them in a new window.
* Also opens all links manually given the "new-window" class in a new window.
* Allows override of behavior if "no-new-window" class is manually added to link. In case of conflict, the "no-new-window" class takes precedence.
* If no automatic labeling of external sites is needed (i.e. all links that should open in a new window are given the "new-window" class manually), delete Step 1.
*/
Drupal.behaviors.newWindow = {
attach: function() {
// -- Step 1: find external links not already labeled and add "external" class -- //
var host_pattern = new RegExp('https?://' + location.host); // get the host of the current site
// go through each link and add class if 1) does not already have a relevant class and 2) has a different host
$('a').not('.external, .new-window, .no-new-window').each(function() {
if ($(this).attr('href') && $(this).attr('href').match(/^https?:\/\//)
&& !$(this).attr('href').match(host_pattern)) {
$(this).addClass('external');
}
});
// -- end Step 1 -- //

// -- Step 2: implement click functionality -- //
$('a.external, a.new-window').click(function() {
if (!$(this).hasClass('no-new-window')) {
window.open(this.href);
return false;
}
});
// -- end Step 2 -- //
}
};
})(jQuery);

9/19/13