$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
You can do this straight with HTML, but that is invalid markup, this takes care of business without invalid code and unnecessary markup.
Or, you can still avoid the validation problems and just append the class target=_blank thing to any links with href attributes starting with http://. The example below only targets links in a #content area. Scoping down like that might be a good idea in case your menus are dynamic and create full URLs.
$("#content a[href^='http://']").attr("target","_blank");
Also note that there are a wide variety of different ways to only target external links.
A slightly different version if you only want to target specific URLs (I use the rel tag “external”):
$('A[rel="external"]')
.click( function() {
window.open( $(this).attr('href') );
return false;
});
Nice snippet Paul, that’s much better, and beautifully unobtrusive and validates in XHTML 1 strict. It’s about time the world stops using obtrusive javascript.
Thank you, Paul! This came in handy.
Very useful technique. Thanks you so much
Here is something that I believe will add a great value. I just tried to ignore any links that belongs to the site and identify the external links straightforward.
Is there a way to resize the window that pops up as well?
Nice solution
This is awesome. Just what I needed for a client’s website. And thanks Paul, that works wonderful.
Here is a snippet we’re using that works similar to Paul’s and adds support for target “_blank”, “parent”, “top” and “popup”
If code is garbled, grab it here: http://www.id3.co.th/js/lib.js (look for “links and popups”)
You then activate it in your pages by adding externallinks(); in your $(document).ready(function(){
If code is garbled, check the source of http://www.id3.co.th/ (look for “.ready(function”)
Hope this helps!
window.onload = externallinks; for nojquery situation
If you have a good reason for opening certain links in a new window and want to use plain HTML you could just switch to the HTML5 doctype.
It’s the little things in life! Small code, huge solution!
target=”_blank” and just forget about xhtml strict, that is dead by the way.
Everyone is talking about HTML5 now.. why do you waste your time with thes insignificant problems?
I agree with you, why bothering with scripts when we already have target”_blank”, moreover it also works for people with js is disabled! Maybe this isnt a concern anymore?
Because, even in 2010, people still don’t understand the role of validation. It’s a tool, not an achievement. Remember the compliance badge craze!?
if you’re using jquery, you should use delagate. that way, you create 1 event binding on the body element, instead of hundreds, one on each link.
code would look something like
$(‘body’).delegate(“a”,”click”,function() {
var a = new RegExp(‘/’ + window.location.host + ‘/’);
if(!a.test(this.href)) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, ‘_blank’);
}
});
Technically it’s a nice solution.
On the other hand it might tempt designers to use it whenever they can. NEVER open up a new window unless it is absolutely necessary or is a 100% user-friendly. Having all external links open up in a new window is neither.
For MooTools it’s very similar:
Good one. I think, this post describes good about it and a perfect solution too!!!
http://praveenbattula.blogspot.com/2010/06/open-all-anchor-links-in-new-window.html
Hi…
Can i have any code to popup an iframe content dynamically……..
Thanks
@nachomaans
How can I have copied the code you given to section .But I am not sure If I follow this line:You then activate it in your pages by adding externallinks(); in your $(document).ready(function(){
Where can I use it?
BTW I tried it in my wordpress blog
I think my comment comes quite late with respect to this post but I have written a small jQuery plugin for the same based on knowledge gain my this post and my readings about jQuery plugin development in the last week or so. Please find the link to the plugin and associated post hope its upto the jQuery plugin development standards.
http://www.uipress.com/extlink-a-jquery-plugin-to-add-target_blank-to-external-and-file-links/
Regards,
Bilal Awan
A small optimization: since the RegExp doesn’t change , move it outside the loop so it is only defined (and compiled) once. No sense in redefining it on each loop occurrence.
Also, it’s worth noting that this only works if all internal links have a full absolute path. Since it compares it to the host name, each link must contain the host name. Relative links in the form /link/to/something or link/to/something will be treated as external links.
I forgot the dollar sign in my code snippet! Here is the correct code:
How to use this code?
I’m know nothing about jQuery, i just paste that code in HTML head, and i get this error in Chrome web inspector:
el Abee.. you have to first include the actual jQuery library and then, make sure the actual code you paste in is within <script></script> tags and that those two tags are within the <head></head> tags. And by the way, including jQuery needs to be done between the head tags too:
sir i have a problem that there are thumbnails in my page when a user clicks it i want to open the larger image of that thumbnail in a div new window tab
Excelente tip, gracias
Here is what we do:
<a href=”somewhere” class=”newWindow”>
and in the jQuery file we use:
function setupNewWindow(){
$(‘.newWindow’).click(function(){window.open($(this).attr(‘href’)); return false;});
}
I tried every variation I possibly could of using $(‘a[rel=”external”]) I could think of. I used double quotes, single quotes, tried using [rel^=”external”] in an attempt to just make the thing look for a link that begins with, I copied and pasted the code instead of typing it out. I made sure that arbitrary jQuery code would work in this scripts place. I made sure that my WordPress enqueue_script was working properly. I tried similar scripts from other websites. I’ve Googled til my fingers bled…
…and still nothing that involves using [rel=””] works for me. I’m using the latest jQuery library from the jQuery CDN (1.7.1 minified @ the time I’m writing this comment). Am I missing something? Does this version of jQuery not pick up on [rel=””]?
If I take the [rel=”external”] out, it works, but for every link (which is to be expected since there’s no conditional). I wrote something else that works that’s a derivative, but the [rel=”external”] just seems so much more elegant and I’d rather use that.
Here’s my script:
Just noticed one thing about the first line in my comment above. $(‘a[rel=”external”]) should be $(‘a[rel=”external”]’).
Any ideas on why this is happening? :-(
Sorry, I could be wrong, but the examples shown here do not work if the attribute with the “external” there is some attribute, such as, “nofollow” or “author”. I used to blog a little bit different code, taken from the plugin:
Tried them all and couldn’t get them to work either…. that is till I tried the code from Konstantin, worked perfect and loaded super fast! Thank you thank you thank you…. saved much time and effort. Question: is it valid? Was usuing simple javascript before but was slow and clunky….(below).
Thanks again Konstantin!!!
This works great, but the code does interfere with some Google Analytics features. For instance, we lost all of our outbound link tracking when using this.
Dang! Were you able to find a way around this?
I have a site with multiple domain, none of the above have a solution for any domain, with or without www.
I have to say that I like your code but I wanted the same effect but with less.
So this is what I used on a project that I am updating.
$(function() {
$(“.targetBlank”).click(function() {
window.open(this.href);
return false;
});
});
You could use this:
$(document).ready(function() {
$(‘.targetBlank’).click(function() {
$(this).target = “_blank”;
window.open(this.href);
return false;
});
});
Yet I chose the first one after testing it out. All you have to do here is add a [class=”targetBlank”] to your links.
I just want to join in the fun with you guys. Great post btw. :D
I just include the script to take the target value (_top,_parent,_self,_blank…) directly.
$(‘a’).each(function() {
var a = new RegExp(‘/’ + window.location.host + ‘/’);
var targets = this.target;
if(!a.test(this.href)) {
$(this).click(function(event) {
window.open(this.href, targets);
return false;
});
}
});
Very nice but you should update this post now with latest jQuery code to make all external links rel=”nofollow”.
Probably the most efficient:
$(this).attr(“target”, “_blank”); u can use this.it works fine…any queries msg me…[email protected]
Love it – thanks for the snippet!
Great. But, I want to open external links in new window except some links. Those links should be opened in _self target. Please help me.
I’m loving this solution, great ideea.
This is a pretty silly statement, as the code in the example adds the “invalid markup”. Whether or not it is in the document source or not, when rendered in the browser it is part of the document either way.
Thanks guys… y’all are awesome!
Thank you so much, this saves me so much time. And learn a few thing myself!
This can actually be simplified to this:
HTMLAnchorElement
also has thehostname
property (which is preferred fromhost
due to some cross-browser issues – IE8 for example will append the port 80 to the hostname even if it is not specified in thehref
).An option to target all external links without requiring classes or
rel
attributes:NOTE: This hasn’t been tested in IE, because quite frankly this is kind of a bad idea in the first place and I don’t care if the links work like links are supposed to work in older browsers.
This post was a great help, thank you. I can now easily add blog badges to my site and know that they are opening in a new window.
If I can alter badge coding to make it open in a new link then anyone can!
I have tryid Mike’s code, but it doesn’t work, anyone else?
Hi, Jacob Magnusson, your code works fine, but it is only working on rel=”external”, but it doesn’t work on something like rel=”external nofollow”, is that any solutions? sorry I’m bad in javascript, just need help. Thank you.
Yo all,
I cant seem to figure out how to open this one up in a new window when dropped. Its a Drag and Drop function. It works, but it does not open up a new window.
Can anyone help me out here?
Hey all, I’m trying to do this on a SharePoint 2007 Webpart page, where I am using the Page Viewer Web Part to include a page of links we use a lot. Now, I want to put some code in a CEWP that will cause on-click of any of those links to open in a new page. Tried your code above but to no avail. Any thoughts?
if the Iframe has external content, how read <a href link block by security error
What if I want to open external site links (further pages) in same div where the site displays, without moving to next page or without changing URL. Just need to open in same div where external site already show.
If you have, as it was in our case, dynamically ajax-loaded links then you could add target=”_blank” on every link added after document is loaded.
Or you could add this fine, well cooked, piece of code to your document ready-function.
Whenever you “mousedown” anywhere in the site, and the target of the “mousedown” is an a-element with no mailto or javascript in the href attribute, check if it is link to an external page. If it is, set it’s attribute target to “_blank”. Scince it’s binded to the document and not the a-element itself, it doesn’t matter if the link is loaded after the document.ready-function.
Alfred, I have a situation.
I get the result in my “showresult” div. What should I do if I want to show other pages inside the same div “showresult” when clicking on the links. I don’t want the links to open on new window or in same window, I want them to open in same div “showresult”.
how to open chrome window using javascript program
if webpage opened in firefox and want to open chrome by click the page that is open in firefox
Thanks for this tip, Chris. The second jQuery snippet, with a mod to the specific URL needed, made it easy to open redirections of specific URLs in a new tab – on a WordPress site where I could add custom javascript but not easily change the Redirection plugin (nor any relevant options). So the jQuery appends the “_blank” to the URL before it reaches the plugin, and then the Redirection plugin does its job. Cheers!
With Vanilla JS:
Here’s a simpler jQuery code:
All these code snippets are great. I have a situation where I need to identify multiple hostnames which are internal links and should not open in a new window. I’m not sure how to modify the code examples for this scenario. Any suggestions would be greatly appreciated.
There’s a major issue with this snippet as it doesn’t consider anchor tags with no href in them. Which is a design decision i.e. using a tags for buttons that only do something with JavaScript.
So the correct code should be like this
Is there a way to prevent this from working on
<a href="javascript:void(0);"
links that are added by plugins (I think to make elements clickable), and which shouldn’t open in a new page? I’m not familiar enough with JavaScript to add an exclusion in for this type of link, but if anyone could help, that would be greatly appreciated!Learned a way to apply your script so that it doesn’t cause problems with “javascript:void(0);” “links” on my site, but it is disabling tracking of external links in Google Analytics (Google Tag Manager implementation with a “Click – Just Links” trigger that uses RegEx to fire when the URL does not contain the domain name).
Is there a way that that the script (or my Universal Analytics GA / GTM setup) can be altered, so that external link clicks are still trackable in Google Analytics (UA, not GA4)?