Open External Links In New Window
$('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.
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:
var a = new RegExp('/' + window.location.host + '/'); $('a').each(function() { if(!a.test(this.href)) { $(this).click(function(event) { event.preventDefault(); event.stopPropagation(); window.open(this.href, '_blank'); }); } });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.
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…yuvarajamsc12@gmail.com
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.