jQuery: make all external link open in new window
February 17, 2009
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
. And sometime, we just can't be ask
. 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.
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
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.
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.
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?
Hi, possible, I actually thought about that before. I will make one as soon as possible. It isn’t hard anyways.
<a href=”your site” rel=”nofollow”></a>
Ex: <a href=”google.com” rel=”nofollow”></a>
The location.hostname part was useful! I forgot about that.
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