Open links in new window automatically in WordPress using JQuery

January 6th, 2009 by Sunil

Sometimes we need to open the external links automatically in our websites. Here I am adding a small snippet for that. JQuery is JavaScript framework using for that. So first you need to include Jquery framework to your page.

For that either you need to download the jquery and add it your page, or you can link directly load the framework using Google code

How we can include JQuery using Google code
Check out this link
http://code.google.com/apis/ajaxlibs/documentation/index.html

Benefits of including JQuery from Google code

  1. It saves on bandwidth
  2. It will load quickly from Google’s CDN.
  3. It will already be cached if the user has visited a site which delivers it from Google code.

Ohh.. I am going out of the subject. Ok, After including Jquery you need to write the below code either in your separate Javascript file or your in the html page.
$(document).ready(function() {
$("a[@href^=http]").each(
function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr('target', '_blank');
}})
});

If you want to add a class on external links for styling differently or add a background to it? It is easy. Just add this code. It will add a class to your external links.
$(document).ready(function() {
$("a[@href^=http]").each(
function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr('target', '_blank');
$(this).addClass(‘external’);
}})
});

I am using this code in my blog. It works well. If you find any bug on it, Please let me know.

[update]

Today I added $(this).attr('rel', 'external nofollow');

So Google may not follow any external link. Now the script should look like this


$(document).ready(function() {
$("a[@href^=http]").each(
function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr('target', '_blank');
$(this).attr('rel', 'external nofollow');
}}
)});

  1. Mr Moo says:

    Except that, as far as I know, the Google spider doesn’t run the JS, so it will follow the external links just fine. Please correct me if I’m wrong.

  2. Pinky says:

    That’s great Sunil. I am a virtual assistant and I have a client who need to open google adsense in a new window. Is this possible with this code?

  3. its v nice sharing brother thx for this