jQuery: make all external link open in new window


February 17, 2009
Don't know what to read next? Check out the list of popular posts. People like them, they should be good.

another tip »

Please check the latest update of this article. jQuery.extLinks: a plugin controls all the links. There’re many improvements which could give visitors a better usibility.

Make a link open in new window is easy but it's also easy to forget Yell. And sometime, we just can't be ask Frown. I saw quite a few websites/blogs have this problem so I come up with a quick fix. And with the help of jQuery, this think couldn't be any easy.

Just insert one line of code into your $(document).ready():

$("a[href*='http://']:not([href*='"+location.hostname+"'])").attr("target","_blank");

or three lines of code if you don't have $(document).ready yet

$(document).ready(function(){
                $("a[href*='http://']:not([href*='"+location.hostname+"'])").attr("target","_blank");
            });

If you want to know more how it work, please read bellow. If not, don't even bother. Tongue out

First we need to select the right link. Sure we don't want all the internal links open in a new window as well. So we start with 

$("a[href*='http://']").attr("target","_blank");

So it's only select all the link with http:// in from of the link.

However the internal link could be http://www.yourdomain.com/content/

So we also need to make sure the link don't contain your domain name as well

$("a[href*='http://']:not([href*='"+location.hostname+"'])").attr("target","_blank");

[/code]

Hope it's help Smile

Share
Under Category: jQuery
Article Tags:
March 2nd, 2009

Nice – but it would be great if you extended this to remove target="_blank" from internal links, just in case they have them turned on. Shouldn’t be hard, just a simple if else statement, but I’m sure someone would find it useful.

March 2nd, 2009

Hi, thank Stephen for comment in my blog. That selector is also remove the internal links already so you don’t need an if statement.

April 3rd, 2009

Another great example I’ve been looking for, would it also be possible to expand on this and show how an external link icon could be attached so as to warn users the link will open in a new window?

April 3rd, 2009
admin

Hi, possible, I actually thought about that before. I will make one as soon as possible. It isn’t hard anyways.

April 22nd, 2009

<a href=”your site” rel=”nofollow”></a>

Ex: <a href=”google.com” rel=”nofollow”></a>

October 30th, 2009

The location.hostname part was useful! I forgot about that.

November 6th, 2009

That’s one way to do it, but did you know about the tag? Does the same thing without any scripting. here’s a link to a post I wrote about it or you can check it out for yourself on the w3c site.

http://tampaseo.wordpress.com/2009/11/06/the-amazing-power-of-the-base-tag/

Trackbacks
Leave a Reply