background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount
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');
    }

  });

});

Eric.London's picture

Here's how you can change your hrefs for any node/add link to https using jQuery:

<?php
$(document).ready(function(){
  $(
'a').each(function(){
   
href = $(this).attr('href');
   
splitA = href.split('/');
    if (
splitA[1]=='node' && splitA[2]=='add') {
      $(
this).attr('href', 'https://'+location.host+href);
    }
  });
});
?>

Syndicate content