Auto open external links in a new window with javascript

Tagged InAllWebJavaScript

A Code snippet to open all external links (that are not an email address) and pdfs in  a new window.

JQuery

$('a', context).not('[href*="mailto:"]').each(function () {
  var local = new RegExp('/' + window.location.host + '/');
  if(!local.test(this.href) || this.href.toLowerCase().match('\\.pdf$')) {
    $(this).click(function (event) {
      event.preventDefault();
      window.open(this.href, '_blank');
    });
  }
});

Drupal Behaviour

  // Open external links and pdfs in a new window.
  Drupal.behaviors.externalNewWin = {
    attach: function (context, settings) {
      $('a', context).not('[href*="mailto:"]').each(function () {
        var local = new RegExp('/' + window.location.host + '/');
        if(!local.test(this.href) || this.href.toLowerCase().match('\\.pdf$')) {
          $(this).click(function (event) {
            event.preventDefault();
            window.open(this.href, '_blank');
          });
        }
      });
    }
  };

 

Next Article