Open links in new window automatically in WordPress using JQuery
Posted by Sunil | Filed under Web Development
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
- It saves on bandwidth
- It will load quickly from Google’s CDN.
- 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');
}}
)});
Tags: external link, google code, Javascript, JQuery, Open new window, Wordpress
5 Responses to “Open links in new window automatically in WordPress using JQuery”
Leave a Reply
You must be logged in to post a comment.












January 15th, 2009 at 2:17 am
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.
May 3rd, 2009 at 5:16 am
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?
June 13th, 2009 at 5:47 pm
its v nice sharing brother thx for this
October 5th, 2009 at 6:36 pm
I think you’re correct
April 4th, 2010 at 12:03 am
i think you are right too. I need a wordpress solution to parse that link.
Thanks